Пример #1
1
 def __init__(self, name, index):
     #these will need to be actual data, and update as you move the object in the world
     self.m_name = name
     self.m_index = index
     #self.m_scale = (1, 1, 0) #we shouldn't really work with scale
     #self.m_position = (0, 0, 0)
     #self.m_width = 100#we could instead use scale and just let them scale instead of drag vertex
     #self.m_height = 100#then we could just calcualte width and height from base w/h and multiple by scale
     #probably the better idea then to let them move around the vertecies
     tempCube = cmds.polyCube(n = name, w = 100, h = 100, d = 0)[0]
     cmds.rotate(0, 90, 0, r=True, os=True)
     self.m_cube = tempCube
     self.m_layout = []
     self.m_effectNumber = -1
     if 'Attack' in self.m_name:
         self.b_isAttack = True
         self.m_effectNumber = 0
     else:
         self.b_isAttack = False
     #self.addUI()
     #red or blue based off of type of box
     lambert = cmds.shadingNode('lambert', asShader=True) 
     cmds.select(self.m_cube)
     if "Attack" in self.m_name:
         cmds.setAttr ( (lambert + '.color'), 1.0, 0.0, 0.0, type = 'double3' )
     else :
         cmds.setAttr ( (lambert + '.color'), 0.0, 0.0, 1.0, type = 'double3' )
         
     cmds.setAttr ( (lambert + '.transparency'), 0.90,0.90,0.90, type= 'double3' )
     
     cmds.hyperShade( assign=lambert )
Пример #2
0
def makeStreetTree(shaders):
    '''
    Creates a tree on a circular platform and with a circular fence around it.
    
    shaders: A list of shaders for the tree crowns.
    On exit: A tree has been created using makeTree(...), a circular platform
             has been created underneath it and a fence around it. Appropriate 
             shaders have been assigned. Everything is united into one polygonal
             object and returned as a tuple with the object name and the node 
             name.
    '''
    tree = makeTree(shaders)
    platform = cmds.polyCylinder(name = "platform",h = 0.1, r = 0.8)
    cmds.move(0.25, y = True)
    cmds.sets(platform[0], edit=True, forceElement="fountainMaterialGroup")
    pole = cmds.polyCube(name = "pole", h = 0.6, w = 0.04, d = 0.04)
    cmds.xform(pole, t = (0.7,0.45,0))
    angle = 360/10.0
    for i in range(1,10):
        pole1 = cmds.polyCube(name = "pole", h = 0.6, w = 0.04, d = 0.04)
        cmds.rotate(angle * i, y = True)
        cmds.move(0.7,0.45,0, os = True)
        pole = cmds.polyUnite(pole, pole1)
    bar = cmds.polyPipe(name = "bar", h = 0.1, r = 0.65, t = 0.04)
    cmds.move(0.65, y = True)
    bar1 = cmds.duplicate(bar[0])
    cmds.move(-0.2, y = True, r = True)
    fence = cmds.polyUnite(pole, bar, bar1)
    cmds.sets(fence[0], edit=True, forceElement="blackMetalGroup")
    streetTree = cmds.polyUnite(tree,platform, fence)
    cmds.delete(streetTree, ch = True)
    return streetTree
Пример #3
0
def addText(obj, t='A', f='Arial-Bold', c=12, rotOffset=[0, 0, 0], posOffset=[-1, 10, 0]):
    '''\n
    obj = transform to recieve text
    t   = text
    f   = font
    c   = color
    '''
    shapes = []
    text = cmds.textCurves(ch=0, f=f, t=t)
    # xform text
    pos = cmds.xform(obj, q=True, rp=True, ws=True)
    rot = cmds.xform(obj, q=True, ro=True, ws=True)
    cmds.xform(text, t=pos, ro=rot)
    # get selection
    cmds.select(text, hi=True)
    sel = cmds.ls(sl=True)
    # find shapes
    for item in sel:
        if cmds.objectType(item) != 'transform':
            # offset
            cmds.rotate(rotOffset[0], rotOffset[1], rotOffset[2], item + '.cv[*]', r=True, eu=True, p=pos)
            cmds.move(posOffset[0], posOffset[1], posOffset[2], item + '.cv[*]', r=True, ls=True, wd=True)
            # assemble
            cmds.setAttr(item + '.overrideEnabled', 1)
            cmds.setAttr(item + '.overrideColor', c)
            cmds.parent(item, obj, r=True, s=True)
            cmds.rename(item, obj + 'Shape')
    # delete left overs
    cmds.delete(text)
Пример #4
0
    def pointOnCurveLocCV(name,curve):
        
        if not cmds.nodeType(curve) == 'shape':
            
            curve = cmds.listRelatives(curve, type = 'shape')[0]
            
        mobject = GenAPI.getMObject(curve)
        iterCVs = om.MItCurveCV(mobject)
        
        while not iterCVs.isDone():

            index = iterCVs.index()
            nameIndex = index + 1            
            moPath = cmds.createNode('motionPath')
            
            moPath = cmds.createNode('motionPath',n = '%s_0%i_MotionPath'%(name,nameIndex))
            cmds.connectAttr('%s.worldSpace[0]'%curve,'%s.geometryPath'%moPath)
            
            locator = cmds.spaceLocator(n = '%s_0%i_MP_Loc'%(name,nameIndex))
            cmds.addAttr(locator[0],ln = "Offset" ,at = 'double')
            cmds.setAttr('%s.Offset'%locator[0], e = True, keyable = True)
            upLocator = cmds.spaceLocator(n = '%s_0%i_MP_Up_Loc'%(name,nameIndex))
                        
            cmds.connectAttr('%s.allCoordinates'%moPath,'%s.translate'%locator[0])
            cmds.connectAttr('%s.rotate'%moPath,'%s.rotate'%locator[0])
            cmds.connectAttr('%s.rotateOrder'%moPath, '%s.rotateOrder'%locator[0])
            
            uValue = MeasuringTool.curveCVtoU(curve,index)
            cmds.setAttr('%s.uValue'%moPath, uValue)
            cmds.setAttr('%s.worldUpType'%moPath, 2)
            cmds.setAttr ('%s.frontAxis'%moPath,0)
            cmds.setAttr ('%s.upAxis'%moPath,2)
            
            offsetMD = cmds.createNode('multiplyDivide', n = '%s_0%i_Offset_MD'%(locator[0],nameIndex))
            cmds.connectAttr('%s.Offset'%locator[0],'%s.input1X'%offsetMD)
            cmds.setAttr('%s.input2X'%offsetMD, 0.1)
            offsetPMA = cmds.createNode('plusMinusAverage', n = '%s_0%i_Offset_PMA'%(locator[0],nameIndex))
            cmds.connectAttr('%s.outputX'%offsetMD,'%s.input1D[0]'%offsetPMA )
            cmds.setAttr('%s.input1D[1]'%offsetPMA,uValue)
            cmds.connectAttr('%s.output1D'%offsetPMA, '%s.uValue'%moPath)
            
            
            locPos = cmds.xform(locator[0], q = True, ws = True, translation = True)
            locOrient = cmds.xform(locator[0], q = True, ws = True, rotation = True)
            
            cmds.setAttr ('%s.worldUpVectorX'%moPath,0)
            cmds.setAttr ('%s.worldUpVectorY'%moPath,0)
            cmds.setAttr ('%s.worldUpVectorZ'%moPath,1)
            cmds.connectAttr('%s.worldMatrix[0]'%upLocator[0], '%s.worldUpMatrix'%moPath)
            
            nullGroup = cmds.group(empty = True, n = '%s_Group'%upLocator[0])
            cmds.move(locPos[0], locPos[1],locPos[2],nullGroup)
            cmds.rotate(locOrient[0],locOrient[1],locOrient[2], nullGroup)
            
            cmds.parent(upLocator[0], nullGroup,r = True)
            cmds.move(0,0,10,upLocator[0], a = True, os = True)
            
            cmds.group(locator[0],nullGroup,n = '%s_0%i_MP_Loc_Group'%(name,nameIndex))
            
            iterCVs.next()
Пример #5
0
	def apply( self, nodes=None, applySettings=None, worldSpace=False ):
		if nodes is None:
			nodes = self._nodeAttrDict.iterkeys()

		for node in nodes:
			if node in self._nodeAttrDict:
				for attr, value in self._nodeAttrDict[ node ].iteritems():
					attrpath = '%s.%s' % (node, attr)
					if objExists( attrpath ):
						setAttr( attrpath, value )

			if worldSpace:
				if node in self._nodeWorldDict:
					if cmd.objectType( node, isAType='transform' ):
						pos, rot, rotateOrder = self._nodeWorldDict[node]
						move( pos[0], pos[1], pos[2], node, ws=True, a=True, rpr=True )

						roAttrpath = '%s.ro' % node
						initialRotateOrder = getAttr( roAttrpath )
						rotateOrderMatches = initialRotateOrder == rotateOrder

						if rotateOrderMatches:
							rotate( rot[0], rot[1], rot[2], node, ws=True, a=True )
						else:
							setAttr( roAttrpath, rotateOrder )
							rotate( rot[0], rot[1], rot[2], node, ws=True, a=True )
							xform( node, ro=constants.ROTATE_ORDER_STRS[ initialRotateOrder ], p=True )
Пример #6
0
def makeRowOfStreetTrees(num, coor, shaders, dir):
    '''
    Makes a row with the specified number of street trees. 
    
    num: Number of street trees in the row.
    coor: A tuple with the x- and z- coordinates the center of the row of trees
          will be located at.
    shaders: A list of shaders for the tree crowns.
    dir: String which specifies if the trees should be placed along the x-axis
         (horisontal) or along the z-axis (vertical).
    On exit: The specified number of trees has been created using makeStreetTree(...),
             and placed in a row at the given coordinates. All of the trees are 
             combined and the resulting object is returned as a tuple with the 
             object name and node name.
    '''
    start =  -(num - 1)/2.0 * 2.8
    tree = makeStreetTree(shaders)
    cmds.xform(tree[0], t = (start, 0, 0), ws = True)
    for i in range(1,num):
        tree1 = makeStreetTree(shaders)
        cmds.xform(tree1[0], t = (start + i * 2.8, 0, 0), ws = True)
        tree = cmds.polyUnite(tree[0], tree1[0])
    cmds.xform(tree[0], centerPivots = True)
    if dir == "vertical":
        cmds.rotate(90, y = True)
    cmds.xform(tree[0], translation = (coor[0], 0,coor[1]), ws = True)
    return tree
Пример #7
0
def goToTarget( first, second ):
    
    tr = cmds.xform( second, q=1, ws=1, piv=1 )[:3]
    ro = cmds.xform( second, q=1, ws=1, ro =1 )[:3]
    
    cmds.move( tr[0], tr[1], tr[2], first, ws=1 )
    cmds.rotate( ro[0], ro[1], ro[2], first, ws=1 )
Пример #8
0
def a_ring():
	
	ring_diameter = 22 # outer diameter 
	ring_thickness = 1.5
	divit_diameter = 1.5
	divit_depth = .75
	ring_height = 4
	#divit_spacing = .5

	divits = []
	cmds.polyPipe(radius=ring_diameter/2, height=ring_height*2, thickness=ring_thickness, name='ring0')
	cmds.setAttr( 'polyPipe1.subdivisionsAxis', 20 )
	
	for x in range(0,6):
		for y in range(0,3):	
			letter = initials[x]
			symbol = letter[y]
			myName = "_c" + str(x) + str(y)
			
			if symbol == 0 :
				cmds.polyCylinder(axis=[0,0,1], radius=(divit_diameter/2), height=divit_depth, name=myName)
			elif symbol == 2:
				cmds.polyCylinder(axis=[0,0,1], radius=(divit_diameter/2), height=ring_thickness * 2.1, name=myName)
		
			if symbol != 1:
				divits.append(myName)	
				y_off = 0
				cmds.move(0,y_off,(ring_diameter/2 - divit_depth/2 + .3),myName)
				cmds.rotate(0,(x*3+y)*20,0,myName, pivot=[0,0,0])
		
	rn = 0;	
	for d in divits[:]:
		print 'ring' + str(rn) + " " + d
		cmds.polyBoolOp('ring' + str(rn), d, op=2, n='ring' + str(rn+1), )
		rn += 1
Пример #9
0
def Circle(name='circle_cnt',group=False,size=1.0):
    ''' Creates a circle shape.
        If group is True, will group control and
        return a list [group,control].
    '''
    
    #creating the curve
    curve=cmds.circle(radius=1,constructionHistory=False)
    
    #transform to standard
    cmds.rotate(0,90,0,curve)
    
    cmds.makeIdentity(curve,apply=True, t=1, r=1, s=1, n=0)
    
    #naming control
    node=cmds.rename(curve,name)
    
    #sizing
    cmds.scale(size,size,size,node)
    cmds.FreezeTransformations(node)
    
    #grouping control
    if group==True:
        grp=cmds.group(node,n=name+'_grp')
        
        return [grp,node]
    
    #return
    return node
Пример #10
0
def create_pointer(m):
    if (BAXER_POINTER == True):
        # import Baxter Pointer model and use it
        try:
            cmds.loadPlugin("objExport")
        except:
            pass
        name = os.path.dirname(os.path.realpath(__file__)) + "/models/baxter_gripper.obj"
        mel.eval('file -import -type "OBJ"  -ignoreVersion -ra true -mergeNamespacesOnClash false -rpr "gripper" -options "mo=1"  -pr "%s";' \
             % name)
        try:
            mel.eval('rename "gripper_Mesh" "pointer' + str(m) + '";')
        except:
            pass
    else:
        # Create a pointer mesh that represents the robot claw
        cmds.polyCone(name="pointer" + str(m), sx=3, r=0.5, h=2)
        cmds.select("pointer" + str(m))
        cmds.rotate("180deg", 0, 0, r=True)
        cmds.move(0, -1, 0, "pointer" + str(m) + ".scalePivot", "pointer" + str(m) + ".rotatePivot")
        cmds.move(0, 1, 0, absolute=True)
        cmds.makeIdentity(apply=True, t=1, r=1, s=1)
    bbx = cmds.xform("table", q=True, bb=True, ws=True)
    cur_size = abs(bbx[3] - bbx[0])
    cmds.scale(cur_size/TABLE_SIZE, cur_size/TABLE_SIZE, cur_size/TABLE_SIZE, "pointer" + str(m), centerPivot = True)
    mel.eval('select -r pointer' + str(m) + '; sets -e -forceElement pointer_matSG;')
    mel.eval("makeCollideNCloth")
Пример #11
0
def placeGem(pt, norm):
	cmds.select('gem')
	cmds.instance()

	r_angle = getRotAngle(norm)
	cmds.rotate(r_angle[0],r_angle[1],r_angle[2], r = True)
	cmds.move(pt[0], pt[1], pt[2])
Пример #12
0
def bestFitPlane(ptList,upVector=(0,1,0)):
	'''
	'''
	# Initialize plane normal
	norm = OpenMaya.MVector()
	pt = OpenMaya.MVector()
	
	# Calculate plane
	for i in range(len(ptList)):
		
		prev = OpenMaya.MVector(ptList[i-1][0],ptList[i-1][1],ptList[i-1][2])
		curr = OpenMaya.MVector(ptList[i][0],ptList[i][1],ptList[i][2])
		norm += OpenMaya.MVector((prev.z + curr.z) * (prev.y - curr.y), (prev.x + curr.x) * (prev.z - curr.z), (prev.y + curr.y) *  (prev.x - curr.x))
		pt += curr
	
	# Normalize result
	norm.normalize()
	pt /= len(ptList)
	
	# Build rotation matrix
	mat = glTools.utils.matrix.buildRotation(norm,upVector,'y','x')
	rot = glTools.utils.matrix.getRotation(mat,'xyz')
	
	# Create Plane
	plane = mc.polyPlane(w=1,h=1,sx=1,sy=1,ax=[0,1,0],cuv=2,ch=False)[0]
	
	# Position Plane
	mc.rotate(rot[0],rot[1],rot[2],plane,os=True,a=True)
	mc.move(pt[0],pt[1],pt[2],plane,ws=True,a=True)
	
	# Return result
	return plane
Пример #13
0
def getAnkleToWorldRotation( obj, fwdAxisName='z', performRotate=False ):
	'''
	ankles are often not world aligned and cannot be world aligned on all axes, as the ankle needs to aim toward
	toe joint.  for the purposes of rigging however, we usually want the foot facing foward (or along one of the primary axes
	'''
	fwd = Vector.Axis( fwdAxisName )
	fwdAxis = getObjectAxisInDirection( obj, fwd )
	basisVectors = getObjectBasisVectors( obj )
	fwdVector = basisVectors[ abs( fwdAxis ) ]

	#determine the directionality of the rotation
	direction = -1 if fwdAxis.isNegative() else 1

	#flatten aim vector into the x-z plane
	fwdVector[ AX_Y ] = 0
	fwdVector = fwdVector.normalize() * direction

	#now determine the rotation between the flattened aim vector, and the fwd axis
	angle = fwdVector.dot( fwd )
	angle = Angle( math.acos( angle ), radian=True ).degrees * -direction

	#do the rotation...
	if performRotate:
		cmd.rotate(0, angle, 0, obj, r=True, ws=True)

	return (0, angle, 0)
Пример #14
0
def rotate(componentList=[],rotate=(0.0,0.0,0.0),pivot='center',userPivot=(0,0,0),worldSpace=False):
	'''
	Rotate a list of components based on the input arguments
	@param componentList: List of components to rotate
	@type componentList: list
	@param rotate: Rotation in degree to apply to the component list
	@type rotate: tuple
	@param pivot: Pivot option for rotation. Valid pivot options are "object", "center" and "user".
	@type pivot: str
	@param userPivot: Pivot position to use if the pivot option is set to "user".
	@type userPivot: tuple
	@param worldSpace: Perform rotation about global world-space axis.
	@type worldSpace: bool
	'''
	# Check componentList
	if not componentList: componentList = mc.ls(componentList,fl=True)
	
	# Determine rotation pivot
	piv = (0,0,0)
	if pivot == 'center':
		piv = getCenter(componentList)
	elif pivot == 'object':
		obj = componentList[0].split('.')[0]
		piv = mc.xform(obj,q=True,ws=True,rp=True)
	elif pivot == 'user':
		piv = userPivot
	else:
		raise Exception('Invalid pivot option - "'+pivot+'"! Specify "object", "center" or "user"!!')
	
	# Rotate Components
	mc.rotate(rotate[0],rotate[1],rotate[2],componentList,p=piv,ws=worldSpace,os=not worldSpace)
 def rotateJoint( self, rotateX, rotateY, rotateZ, rotateRelative=False ):
   objs = cmds.ls( selection=True )
   try:
       pm.mel.eval( """
           setToolTo $gRotate;
           manipRotateValues Rotate;
           toolPropertyShow;
           changeToolIcon;
       """ )
   except:
       print( "switching to rotate tool (with error correction via exception handling)" )
   try:
       pm.mel.eval( """
           setToolTo $gRotate;
           manipRotateValues Rotate;
           toolPropertyShow;
           changeToolIcon;
       """ )
   except:
       print( "(...continuing error correction via exception handling)" )
   for i in objs:
       try:
           cmds.rotate( rotateX, rotateY, rotateZ , i + ".rotateAxis", os=True, relative=rotateRelative  )
       except:
           try:
               cmds.rotate( rotateX, rotateY, rotateZ , i, os=True, relative=rotateRelative  )
           except:
               print( "Couldn't rotate joint.")
               print(  traceback.format_exc(  )  )
Пример #16
0
def createArrow(name=None, thickness=0.1, length=2, vector=[1,0,0], point=[0,0,0]):
    '''
    Creates an arrow in the direction of the vector
    Example:
    arrow = createArrow(vector=[0,1,0], length=4)
    '''
    if not name:
        name = 'arrow_CTRL'
    #calc length for thickness
    ratio = length/thickness
    cyl = cmds.cylinder(radius=thickness, sections=4, heightRatio=ratio, pivot=[length/2, 0, 0], ch=0)[0]
    cone = cmds.cone(radius=thickness*2, sections=4, ch=0, pivot=(length*1.0005,0,0))[0]
    xform = cmds.createNode('transform', ss=1, name=name)
    
    shapes = []
    transforms = []
    for node in [cone,cyl]:
        shapes.append(cmds.listRelatives(node, fullPath=1, shapes=1)[0])
        transforms.append(node)
    cmds.parent(shapes, xform, r=1, s=1)
    rotateBy = cmds.angleBetween(euler=True, v1=(1,0,0), v2=vector)
    cmds.rotate(rotateBy[0], rotateBy[1], rotateBy[2], xform)
    cmds.xform(xform, t=point)
    cmds.delete(transforms)
    return xform
def makeRobot():
    MayaCmds.polyCube(name="head")
    MayaCmds.move(0, 4, 0, r=1)

    MayaCmds.polyCube(name="chest")
    MayaCmds.scale(2, 2.5, 1)
    MayaCmds.move(0, 2, 0, r=1)
    MayaCmds.polyCube(name="leftArm")
    MayaCmds.move(0, 3, 0, r=1)
    MayaCmds.scale(2, 0.5, 1, r=1)
    MayaCmds.duplicate(name="rightArm")
    MayaCmds.select("leftArm")
    MayaCmds.move(1.25, 0, 0, r=1)
    MayaCmds.rotate(0, 0, 32, r=1, os=1)
    MayaCmds.select("rightArm")
    MayaCmds.move(-1.25, 0, 0, r=1)
    MayaCmds.rotate(0, 0, -32, r=1, os=1)
    MayaCmds.select("rightArm", "leftArm", "chest", r=1)
    MayaCmds.group(name="body")

    MayaCmds.polyCube(name="bottom")
    MayaCmds.scale(2, 0.5, 1)
    MayaCmds.move(0, 0.5, 0, r=1)
    MayaCmds.polyCube(name="leftLeg")
    MayaCmds.scale(0.65, 2.8, 1, r=1)
    MayaCmds.move(-0.5, -1, 0, r=1)
    MayaCmds.duplicate(name="rightLeg")
    MayaCmds.move(1, 0, 0, r=1)
    MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1)
    MayaCmds.group(name="lower")

    MayaCmds.select("head", "body", "lower", r=1)
    MayaCmds.group(name="robot")
Пример #18
0
def crystalise(base):
    '''
    Adds hexagonal crystals to a branch
    
    base : The branch to be crystallised
    
    A crystal is created by scaling the top and bottom rings of vertices of a 
    cylinder. The crystal is aligned to the base branch and scaled to match. 
    The crystal is duplicated, randomly distributed along the branch and scaled 
    relative to their positioning. The crystals are combined with the base branch 
    mesh and this object is returned.
    '''
    crystal=[cmds.polyCylinder(r=1,sx=6,sy=2)[0]]
    cmds.polySoftEdge(crystal[0], a=0)
    cmds.scale(0.6,0.3,0.6,crystal[0]+'.f[12:13]',r=1)
    [(tx,ty,tz)] = cmds.getAttr(base+'.translate')
    [(rx,ry,rz)] = cmds.getAttr(base+'.rotate')
    cmds.move(tx,ty,tz,crystal[0])
    cmds.rotate(rx,ry,rz,crystal[0])
    [x1,y1,z1,x2,y2,z2] = cmds.xform(base+'.vtx[0:1]',q=1,t=1,ws=1)
    baseScale = cmds.getAttr(base+'.scaleX')
    cmds.scale(0.5,0.2,0.5,crystal[0])
    length = ((x2-x1)**2+(z2-z1)**2)**0.5
    for i in range(0,6):
        crystal[len(crystal):]=[cmds.duplicate(crystal[0])[0]]
    for x in crystal:
        dist = (random.random())
        cmds.move(length*dist,0,0,x,os=1,r=1,wd=1)
        size = (1.5-dist)*(length/3)
        cmds.scale(size,size,size,x,r=1)
        cmds.rotate(0,30,0,x,r=1)
    crystal += [base]
    return combineParts(crystal,base)
Пример #19
0
def evenlyDivideCurve( curve, numDiv ):
    """ Divides a curve into numDiv.
        Assumes there are two CVs at the start and end of the curve """
    # first, move the curve to the origin
    translation = mc.xform(curve, q=True, ws=True, translation=True)
    rotation = mc.xform(curve, q=True, ws=True, rotation=True)
    mc.move(0, 0, 0, curve)
    mc.rotate(0, 0, 0, curve)

    # get the curve info node
    infoNode = getCurveInfoNode(curve)
    Knots = list( mc.getAttr( infoNode+".knots" )[0] )
    CVs = mc.getAttr( curve+".cv[*]" )
    numOrigCVs = len(CVs)
    numOrigKnots = len(Knots)

    if( not numOrigCVs == 4 ):
        print("ERROR: original curve must have exactly 4 CVs")
        return
    else:
        for p in range(0,(numDiv-numOrigCVs+4+1)):
            percent = (p-1)/float(numDiv-2)
            u = findParamAtArcPercent( curve, percent )
            if p < 2 or p >= (numDiv-numOrigCVs+3):
                CVs[p] = tuple(mc.pointOnCurve(curve, parameter=u))
            else:
                CVs.insert(p, tuple(mc.pointOnCurve(curve, parameter=u)) )
                Knots.insert(p+1, u)
    curve = mc.curve( curve,r=True, p=CVs, k=Knots)

    mc.move(translation[0], translation[1], translation[2], curve)
    mc.rotate(rotation[0], rotation[1], rotation[2], curve)
    return curve
Пример #20
0
def align():
	obj1, obj2 = cmds.ls(selection=True, o=True)
	objPos = cmds.xform(obj2, q=1, ws=1, rp=1)
	objRot = cmds.xform(obj2, q=1, ro=True)
	cmds.move(objPos[0], objPos[1], objPos[2], obj1, rpr=True)
	cmds.rotate(objRot[0], objRot[1], objRot[2], obj1, r=True)
	cmds.select(obj1)
Пример #21
0
def doPositionLocator(locatorName,locInfo):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Position a locator with locator info generated from returnInfoForLoc

	ARGUMENTS:
	locatorName(string)
	locInfo(dict)

	RETURNS:
	success(bool)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	if search.returnObjectType(locatorName) == 'locator':
		objTrans = locInfo['position']
		objRot = locInfo['rotation']
		correctRo = locInfo['rotationOrder']

		mc.move (objTrans[0],objTrans[1],objTrans[2], locatorName)
		mc.setAttr ((locatorName+'.rotateOrder'), correctRo)

		#Rotate
		if locInfo['objectType'] == 'polyFace':
			constBuffer = mc.normalConstraint((locInfo['createdFrom']),locatorName)
			mc.delete(constBuffer[0])
		else:
			mc.rotate (objRot[0], objRot[1], objRot[2], locatorName, ws=True)

		return True
	else:
		guiFactory.warning('Not a locator.')
		return False
Пример #22
0
def makeFlake(branches,radius):
    '''
    Creates a single snowflake
    
    branches : number of side branches
    radius   : radius of the snowflake
    
    A cube is created and transformed to taper with a diamond cross-section. 
    It is passed to flakeIterate to generate 1/6 of the snowflake. This branch 
    is duplicated and rotated around the centre to create the full snowflake. 
    The parts are combined, the flake is scaled and transformations are frozen. 
    The snowflake name is returned.
    '''
    name=cmds.polyCube()[0]
    cmds.rotate(45,0,0,name,r=1)
    cmds.move(0.5,0,0,name+'.vtx[0:7]',r=1)
    cmds.scale(0.7,0.2,0.1,p=[0,0,0],r=1)
    cmds.scale(1,0.7,0.7,name+'.f[4]',r=1,p=[0,0,0])
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    partList=flakeIterate(name,7,random.uniform(30,70),0.7)
    branches=[combineParts(partList,'branch')]
    for i in range(1,6):
        branches[len(branches):]=[cmds.duplicate('branch')[0]]
        cmds.rotate(0,i*60,0,branches[-1],r=1)
    flake = combineParts(branches,'snowflake')
    scale = radius/6
    cmds.scale(scale,scale,scale,flake)
    cmds.makeIdentity(flake,apply=True, s=1, n=0)
    return flake
def loadSelectedObj():
    cmds.file(new=True, pm=False, force=True)
    selected = cmds.optionMenu(loadComponentsMenu, q=True, v=True)
    global furniture
    global furnitureFilePath
    path = os.path.split(furnitureFilePath)[0] + "/meshes/furniture/"
    menuItems = cmds.optionMenu(componentsMenu, q=True, itemListLong=True)
    cmds.textField(objNameInput, tx=selected.split(".")[0].split("/")[1], e=True)
    if menuItems:
        cmds.deleteUI(menuItems)
    for comp in furniture["components"] :
        if comp["src"] == selected :
            global currentComponent
            componentDef = ""

            with open(os.path.split(furnitureFilePath)[0]+"/"+comp["src"], "r") as componentFile:
                componentDef = componentFile.read()
            currentComponent = json.loads(componentDef)

            cmds.file(path + currentComponent["src"], i=True)
            for con in currentComponent["connectors"]: #for connectors in the current objects connectors
                for types in con["componentTypes"]:
                    cmds.menuItem(p=componentsMenu, label=types)
                for jnt in con["out"]:
                    loc = cmds.spaceLocator()
                    cmds.move(jnt["position"][0], jnt["position"][1], jnt["position"][2], loc)
                    cmds.scale(jnt["scale"][0], jnt["scale"][1], jnt["scale"][2], loc)
                    cmds.rotate(jnt["rotation"][0], jnt["rotation"][1], jnt["rotation"][2], loc)
    updateJson()
    selectLocators()
    cmds.textField(typeInput, tx=currentComponent["type"], e=True)
Пример #24
0
def modify_surface():
    
    perlin = True
    sel = mc.ls(selection=True,long=True)
    for verts in sel:
        totalVerts = mc.polyEvaluate(verts, vertex=True)
        for number in xrange(totalVerts):
            if perlin == True:
				frequency = 1.0
				amplitude = 1.5
				octaves = 8
				for o in xrange(octaves):
				    randX = random.triangular(-0.2 , 0.0, 0.2)
				    posX = perlinNoise(randX ,0,0)
				    
				    randY = random.triangular(-0.4 , 0.0, 0.6)
				    posY = perlinNoise(0,randY,0)
				    
				    randZ = random.triangular(-0.2 , 0.0, 0.2)
				    posZ = perlinNoise(0,0,randZ)
				    
				    posX *= frequency
				    posY *= frequency
				    posZ *= frequency 
				    
				    mc.select(verts+'.vtx[{number}]'.format(number=number))
				    mc.move(posX,posY*amplitude,posZ,relative=True)
				    mc.rotate(posY*amplitude,y=True)
    mc.select(sel, replace=True)
    mc.makeIdentity(s=True, a=True, t=True,r=True)
Пример #25
0
def getAnkleToWorldRotation( ankle, fwdAxisName='z', performRotate=False ):
	'''
	ankles are often not world aligned and cannot be world aligned on all axes, as the ankle needs to aim toward
	toe joint.  for the purposes of rigging however, we usually want the foot facing foward (or along one of the primary axes
	'''
	fwd = Vector.Axis( fwdAxisName )

	#flatten aim vector into the x-z plane
	aimVector = getAimVector( ankle )
	aimVector[ 1 ] = 0
	aimVector = aimVector.normalize()

	#now determine the rotation between the flattened aim vector, and the fwd axis
	angle = aimVector.dot( fwd )
	angle = Angle( math.acos( angle ), radian=True ).degrees

	#determine the directionality of the rotation
	direction = 1
	sideAxisName = 'x' if fwdAxisName[-1] == 'z' else 'z'
	if aimVector.dot( Vector.Axis( sideAxisName ) ) > 0:
		direction = -1

	angle *= direction

	#do the rotation...
	if performRotate:
		cmd.rotate(0, angle, 0, ankle, r=True, ws=True)

	return (0, angle, 0)
Пример #26
0
 def test_constrainLocators(self):
     #--- Setup the scene
     startJnt = cmds.joint(n='startJnt',p=(3, 0, 0))
     endJnt = cmds.joint(n='endJnt',p=(3, 5, -2))
     upObj = cmds.joint(n='upJnt',p=(4, 0, 0))
     
     #--- Create the locators... tsk, tsk, external dependency, but why repo so much code here!?
     result = self.rig._createLocators(name='test', start=startJnt, end=endJnt, startUpObj=upObj)
     
     #--- Call method, get results
     result = self.rig._constrainLocators(locators=result)
     
     #--- Check Results
     self.test.assertConstrained('test_btmLoc_pos','test_topLoc_aim',type='aim')
     self.test.assertConstrained('test_topLoc_pos','test_btmLoc_aim',type='aim')
     self.test.assertConstrained('test_topLoc_pos','test_midLoc_aim',type='aim')
     
     self.test.assertConstrained('test_topLoc_pos','test_midLoc_pos',type='point')      
     self.test.assertConstrained('test_btmLoc_pos','test_midLoc_pos',type='point')       
     
     self.test.assertConstrained('test_topLoc_up','test_midLoc_up',type='point')       
     self.test.assertConstrained('test_btmLoc_up','test_midLoc_up',type='point')
     
     btmPos = cmds.xform('test_btmLoc_up', q=1,ws=1, rp=1)
     self.test.assertFloatListAlmostEqual(btmPos,[13,0,0])
     
     # Twist the top
     cmds.rotate(0,45,0,'test_topLoc_pos')
     topPos = cmds.xform('test_topLoc_up', q=1,ws=1, rp=1)
     midPos = cmds.xform('test_midLoc_up', q=1,ws=1, rp=1)
     avgPos = [(topPos[0]+btmPos[0])/2.0, (topPos[1]+btmPos[1])/2.0, (topPos[2]+btmPos[2])/2.0]
     self.test.assertListEqual(avgPos, midPos)
Пример #27
0
def rotCtrlShapeX (_isPositive):
    sel = cmds.ls(selection = True)
    for controlName in sel:
        #clear the selection
        
        cmds.select(clear = True)
        #error catching, in case something other than a  
        #curve or circle is selected
        
        cmds.selectMode(component = True)
        try:
            #selects the cvs in a nurbs curve or circle
            
            cmds.select(controlName+".cv[0:"+ str(getCVs(controlName)-1) + "]")
            
        except:
            #prints the reason for the failure
            
            print "Button not Activated: Control to Scale Must be a Curve or Circle"
        
        #does the rotation
        
        if (_isPositive == True):
            cmds.rotate(90,0,0, os = True, r = True)
        else:
            cmds.rotate(-90,0,0, os = True, r = True)
                
    #select all of the controls that were originally selected
    
    cmds.selectMode(object = True)
    cmds.select(sel)
Пример #28
0
    def draw(self):

            circle1 = cmds.circle( nr=(1, 0, 0), c=(0, 0, 0), sw=self.sweep, r=self.start_radius )
            circle2 = cmds.circle( nr=(1, 0, 0), c=(0, 0, 0), sw=self.sweep, r=self.end_radius )

            l1 = cmds.loft(circle1, circle2)

            # curves
            crv = cmds.curve(p=[(0, self.start_radius, 0), (0, self.end_radius, 0)], degree=1)
            crv2 = cmds.duplicate(crv)
            cmds.rotate(str(self.sweep) + 'deg', 0, 0, r=True)

            extrusions = []

            for e in [circle1, circle2, crv, crv2]:
                extrusions.append(cmds.extrude(e, et=0, d=(1,0,0), l=self.height))
                cmds.delete(e)

            pieces = extrusions + [l1]
            group = cmds.group(*[e[0] for e in pieces])

            cmds.move(0,0,0, group+".scalePivot",group+".rotatePivot", absolute=True)
            cmds.setKeyframe(group, attribute='rotateX', t='0sec', value=self.rotation)

            return (pieces, group)
Пример #29
0
  def generate(cls, *args):
    components = []
    boolean = []
    width = cmds.intSliderGrp(cls.get_prefix() + Labels["width_label"], query=True, value=True)
    rgb = cmds.colorSliderGrp(cls.get_prefix() + Labels["color_label"], query=True, rgbValue=True)

    block_width = width * Constants["block_width_unit"]
    block_height = Constants["block_height_unit"]
    block_depth = Constants["block_depth_unit"]

    for x in range(0, width):
      stub = cmds.polyCylinder(name=get_unique_name(cls.get_prefix(), "Stub"), radius=Constants["stub_radius"], height = Constants["stub_height"])
      components.append(stub[0])
      cmds.move(Constants["block_width_unit"] * x + half(Constants["block_width_unit"]), half(Constants["block_height_unit"]) + half(Constants["stub_height"]), half(Constants["block_depth_unit"]), stub[0])
      
    for x in range(0, width-1):
      hole = cmds.polyCylinder(name=get_unique_name(cls.get_prefix(), "Hole"), radius=Constants["perforation_radius"], height=Constants["block_depth_unit"] + 0.2)
      boolean.append(hole[0])
      cmds.rotate('90deg', 0, 0, hole[0])
      cmds.move(Constants["block_width_unit"] * x + Constants["block_width_unit"], 0, half(Constants["block_depth_unit"]), hole[0])

    cube = cmds.polyCube(sx=5,sy=2,sz=2,name=get_unique_name(cls.get_prefix(), "block"), width=block_width, height=block_height, depth=block_depth)
    components.append(cube[0])
    cmds.move(half(width * Constants["block_width_unit"]), 0, half(Constants["block_depth_unit"]), cube)
    solid = cmds.polyUnite(components, name=get_unique_name(cls.get_prefix(), ""))
    boolean_group = cmds.polyUnite(boolean, name=get_unique_name(cls.get_prefix(),"boolean"))
    final = cmds.polyBoolOp( solid[0], boolean_group[0], op=2, n=get_unique_name(cls.get_prefix(), "") )

    shader = cmds.shadingNode('blinn', asShader=True, name=get_unique_name(cls.get_prefix(),"mat"))
    cmds.setAttr(shader + ".color", rgb[0],rgb[1],rgb[2], type='double3')
    cmds.select(final[0], r=True)
    cmds.hyperShade(assign=shader)
Пример #30
0
def bestFitPlaneCreate(ptList,upVector=(0,1,0)):
	'''
	Create a best fit plane from a specified set of points.
	@param ptList: List of points to calculate best fit plane from.
	@type ptList: list
	@param upVector: Up vector for orientation reference.
	@type upVector: tuple or list
	'''
	
	# Calculate Plane Center and Normal
	p = glTools.tools.center.centerPoint_average(ptList)
	pt = OpenMaya.MVector(p[0],p[1],p[2])
	n = bestFitPlaneNormal(ptList)
	norm = OpenMaya.MVector(n[0],n[1],n[2])
	
	# Build rotation matrix
	mat = glTools.utils.matrix.buildRotation(norm,upVector,'y','x')
	rot = glTools.utils.matrix.getRotation(mat,'xyz')
	
	# Create Plane
	plane = mc.polyPlane(w=1,h=1,sx=1,sy=1,ax=[0,1,0],cuv=2,ch=False)[0]
	
	# Position Plane
	mc.rotate(rot[0],rot[1],rot[2],plane,os=True,a=True)
	mc.move(pt[0],pt[1],pt[2],plane,ws=True,a=True)
	
	# Return result
	return plane
Пример #31
0
    def test_constrainLocators(self):
        #--- Setup the scene
        startJnt = cmds.joint(n='startJnt', p=(3, 0, 0))
        endJnt = cmds.joint(n='endJnt', p=(3, 5, -2))
        upObj = cmds.joint(n='upJnt', p=(4, 0, 0))

        #--- Create the locators... tsk, tsk, external dependency, but why repo so much code here!?
        result = self.rig._createLocators(name='test',
                                          start=startJnt,
                                          end=endJnt,
                                          startUpObj=upObj)

        #--- Call method, get results
        result = self.rig._constrainLocators(locators=result)

        #--- Check Results
        self.test.assertConstrained('test_btmLoc_pos',
                                    'test_topLoc_aim',
                                    type='aim')
        self.test.assertConstrained('test_topLoc_pos',
                                    'test_btmLoc_aim',
                                    type='aim')
        self.test.assertConstrained('test_topLoc_pos',
                                    'test_midLoc_aim',
                                    type='aim')

        self.test.assertConstrained('test_topLoc_pos',
                                    'test_midLoc_pos',
                                    type='point')
        self.test.assertConstrained('test_btmLoc_pos',
                                    'test_midLoc_pos',
                                    type='point')

        self.test.assertConstrained('test_topLoc_up',
                                    'test_midLoc_up',
                                    type='point')
        self.test.assertConstrained('test_btmLoc_up',
                                    'test_midLoc_up',
                                    type='point')

        btmPos = cmds.xform('test_btmLoc_up', q=1, ws=1, rp=1)
        self.test.assertFloatListAlmostEqual(btmPos, [13, 0, 0])

        # Twist the top
        cmds.rotate(0, 45, 0, 'test_topLoc_pos')
        topPos = cmds.xform('test_topLoc_up', q=1, ws=1, rp=1)
        midPos = cmds.xform('test_midLoc_up', q=1, ws=1, rp=1)
        avgPos = [(topPos[0] + btmPos[0]) / 2.0, (topPos[1] + btmPos[1]) / 2.0,
                  (topPos[2] + btmPos[2]) / 2.0]
        self.test.assertListEqual(avgPos, midPos)
Пример #32
0
    def build(self):
        #create the ribbon rig
        self.setup()

        #create the plane
        self.plane = cmds.nurbsPlane(n=("{0}_surf".format(self.nameSpace)),
                                     u=1,
                                     v=3,
                                     w=1,
                                     lr=float(self.jointAmmount) - 1)
        cmds.move(0, self.middleList, 0)
        cmds.rotate(0, 90, 0)
        cmds.makeIdentity(apply=True)
        self.planeShape = cmds.listRelatives(self.plane, s=True)
        #cmds.delete(constructionHistory=True)

        #create 3 follicles
        self.follicles.append(
            self.createFollicle(self.planeShape[0], "lo", parameterV=0.175))
        self.follicles.append(
            self.createFollicle(self.planeShape[0], "mid", parameterV=0.5))
        self.follicles.append(
            self.createFollicle(self.planeShape[0], "up", parameterV=0.825))
        self.follicles.append(
            self.createFollicle(self.planeShape[0], "end", parameterV=1))

        #skin the plane
        cmds.skinCluster(self.ribbonJnts[0],
                         self.ribbonJnts[1],
                         self.ribbonJnts[-1],
                         self.plane[0],
                         dr=3,
                         mi=2,
                         sw=1)

        #parentConstraint follicle over midCtrl
        #cmds.parentConstraint( self.follicleTransform, self.getMidZeroGroup, mo=True )
        cmds.parent(self.plane[0], self.masterGrp)

        #parent follicle
        #group follicles
        folGrp = cmds.createNode('transform',
                                 n=('grpFol_{0}').format(self.nameSpace))
        cmds.parent(self.follicles[0], self.follicles[1], self.follicles[2],
                    self.follicles[3], folGrp)
        cmds.parent(folGrp, self.masterGrp)

        #parent all Groups under master
        cmds.parent(self.ctrlGrp, self.masterGrp)
        cmds.parent(self.midLoc.getZeroGroup1(), self.masterGrp)
Пример #33
0
def convertLocalKeyToWorldKey_basedOnWorld(worldCtl):

    import sgBFunction_dag
    import sgBModel_data

    if worldCtl[-9:] != 'World_CTL':
        cmds.warning("Select World_CTL")
        return None

    targetCtls = [
        'Fly_CTL', 'Root_CTL', 'Leg_L_FK0_CTL', 'Leg_R_FK0_CTL',
        'Leg_L_PoleV_CTL', 'Leg_R_PoleV_CTL', 'Leg_L_IK_CTL', 'Leg_R_IK_CTL',
        'Arm_L_IK_CTL', 'Arm_R_IK_CTL', 'Arm_L_PoleV_CTL', 'Arm_R_PoleV_CTL',
        'Arm_L_FK0_CTL', 'Arm_R_FK0_CTL'
    ]

    ns = worldCtl.replace('World_CTL', '')

    worldTranslates = []
    worldRotates = []
    for targetCtl in targetCtls:
        trans = cmds.xform(targetCtl, q=1, ws=1, t=1)
        rot = cmds.xform(targetCtl, q=1, ws=1, ro=1)
        worldTranslates.append(trans)
        worldRotates.append(rot)

    cmds.setAttr(worldCtl + '.t', 0, 0, 0)
    cmds.setAttr(worldCtl + '.r', 0, 0, 0)

    for i in range(len(targetCtls)):
        targetCtl = targetCtls[i]

        attrs = cmds.listAttr(targetCtl, k=1)

        translateOn = False
        rotateOn = False

        for attr in attrs:
            if attr == 'translateX':
                translateOn = True
            elif attr == 'rotateX':
                rotateOn = True

        if translateOn:
            wt = worldTranslates[i]
            cmds.move(wt[0], wt[1], wt[2], targetCtl, ws=1)
        if rotateOn:
            wr = worldRotates[i]
            cmds.rotate(wr[0], wr[1], wr[2], targetCtl, ws=1)
Пример #34
0
def trs_matching(node=None, sel_org=True):
    global matching_obj
    global matching_mode
    global child_comp_flag
    # print matching_mode, matching_obj
    mode = matching_mode
    if node is None:
        mached_obj = cmds.ls(sl=True, l=True, type="transform")
    else:
        # print 'muched obj', node
        mached_obj = node
    if not mached_obj:
        if sel_org:
            finish_matching()
        return
    else:
        if isinstance(mached_obj, list):
            mached_obj = mached_obj[0]
    # print 'trs matching :', mached_obj
    scl = cmds.xform(mached_obj, q=True, s=True, ws=True)
    rot = cmds.xform(mached_obj, q=True, ro=True, ws=True)
    pos = cmds.xform(mached_obj, q=True, t=True, ws=True)
    for obj in matching_obj:
        if mode == "scale" or mode == "all":
            cmds.scale(1.0, 1.0, 1.0, obj, pcp=True)
            ws_scl = cmds.xform(obj, q=True, s=True, ws=True)
            cmds.scale(
                scl[0] / ws_scl[0],
                scl[1] / ws_scl[1],
                scl[2] / ws_scl[2],
                obj,
                pcp=child_comp_flag,
            )
        if mode == "rotate" or mode == "all":
            cmds.rotate(rot[0],
                        rot[1],
                        rot[2],
                        obj,
                        ws=True,
                        pcp=child_comp_flag)
        if mode == "translate" or mode == "all":
            cmds.move(pos[0],
                      pos[1],
                      pos[2],
                      obj,
                      ws=True,
                      pcp=child_comp_flag)
    if sel_org:
        finish_matching()
Пример #35
0
def createModel():
    #the balloon
    cmds.move(0,10,3.2,bhead)
    cmds.scale(1,1.15,1,bhead)
    applyColor('bhead',0.8,0,0)
    
    cmds.move(0,5.5,3.2,bstring)
    cmds.group('bhead','bstring',n='balloon')
    applyColor('bstring',0.1,0.1,0.1)
    
    #the head
    cmds.move(0, 5, 0, head)
    applyColor('head',1,0.8,0.1)
    
    cmds.move(1.1,5.2,0.5,eye_l)
    cmds.move(1.1,5.2,-0.5,eye_r)
    cmds.group('head','eye1','eye2', n='headGroup')
    applyColor('eye1',0,0,0)
    applyColor('eye2',0,0,0)
    
    #the body
    cmds.scale(1, 1.5, 1, body)
    cmds.move(0,2,0,body)
    applyColor('body',0.9,0.9,0.9)
    
    cmds.rotate(65, 0, 0, arm_l)
    cmds.rotate(80, 0, 0, arm_r)
    cmds.move(0,3,2, arm_l)
    cmds.move(0,2.5,-2,arm_r)
    applyColor('arm1',1,0.8,0.1)
    applyColor('arm2',1,0.8,0.1)
    
    cmds.rotate(100, 30, 0, leg_l)
    cmds.rotate(80, -30, 0, leg_r)
    cmds.move(1,0.4,2, leg_l)
    cmds.move(1,0.4,-2,leg_r)
    applyColor('leg1',1,0.7,0)
    applyColor('leg2',1,0.7,0)
    cmds.group('body','arm1','leg1','leg2', n='bodyGroup')
    
    #the rattle
    cmds.move(0, 3.8, -3.7, rattle)
    cmds.move(0, 3, -3.7, stick)
    applyColor('rattle',0.5,0.5,1)
    applyColor('stick',0.2,0.2,0)
    cmds.group('rattle', 'stick', n='rattleGroup')
    cmds.rotate(-20, 0, 0, 'rattleGroup')
    cmds.group('arm2','rattleGroup', n='shake')
    cmds.group('headGroup','bodyGroup','shake', n='kid')
Пример #36
0
    def createStone(self):
        """ This method creates the form of stone. """

        # create a sphere
        subdivisionsX = 40
        subdivisionsY = 50
        if self.typeStone == 'small':
            size = 6.
        if self.typeStone == 'big':
            size = 9.
        self.currentStone = mc.polySphere(sx=subdivisionsX,
                                          sy=subdivisionsY,
                                          r=size)

        # change its form
        mc.scale(1, 0.5, 0.6, r=True)
        mc.move(0, size / 3.4, 0, r=True)
        stoneRY = random.randrange(0, 360)
        mc.rotate(0, stoneRY, 0, r=True, os=True)

        mc.softSelect(softSelectEnabled=True, ssd=4, sud=0.5)
        #mc.softSelect( ssd=0.6, sud=0.3 )

        for i in range(20):
            vertexNumber = random.randrange(
                0, self.totalNumberVertexSphere(subdivisionsX, subdivisionsY))
            moveX = size / 200 * random.randrange(10, 20)
            moveY = size / 200 * random.randrange(5, 20)
            moveZ = size / 200 * random.randrange(5, 20)
            mc.select(self.currentStone[0] + '.vtx[' + str(vertexNumber) + ']')
            mc.move(moveX, moveY, moveZ, r=True)

        mc.softSelect(softSelectEnabled=False)
        mc.displaySmoothness(divisionsU=3,
                             divisionsV=3,
                             pointsWire=16,
                             pointsShaded=4,
                             polygonObject=3)

        # Modify -> Freeze Transformation
        mc.select(self.currentStone[0])
        mc.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1)

        # delete history
        maya.mel.eval("DeleteHistory")

        mc.select(clear=True)

        return self.currentStone[0]
Пример #37
0
def CreateWrists():    

    #left
    L_wrist_ctrl1 = base.circle(nr = (0,1,0), c = (0,0,0), radius = 1, degree = 1, s = 16, name = "CTRL_L_Wrist0")
    L_wrist_ctrl2 = base.circle(nr = (1,0,0), c = (0,0,0), radius = 1, degree = 1, s = 16, name = "CTRL_L_Wrist1")
    L_wrist_ctrl3 = base.circle(nr = (0,0,1), c = (0,0,0), radius = 1, degree = 1, s = 16, name = "CTRL_L_Wrist2")
    L_wrist_ctrl = base.group(em = True, name ="CTRL_L_Wrist")
    curves = [L_wrist_ctrl1,L_wrist_ctrl2, L_wrist_ctrl3]
    
    for cv in curves:
        crvShape = base.listRelatives(cv, shapes = True)
        base.parent(crvShape, L_wrist_ctrl, s = True, r = True)
        base.delete(cv)
        
    base.addAttr(shortName = "PV", longName = "Elbow_PV", attributeType = 'double', defaultValue = 0, minValue = -100, maxValue = 100, keyable = True)
    base.scale(0.07, 0.07, 0.07, L_wrist_ctrl)
    
    l_wristPos = base.xform(base.ls("RIG_L_Wrist"), q = True, t = True, ws = True)
    l_wristRot = base.joint(base.ls("RIG_L_Wrist"), q = True, o = True)
    
    base.move(l_wristPos[0], l_wristPos[1], l_wristPos[2], L_wrist_ctrl)
    base.rotate(0, 0, l_wristRot[0], L_wrist_ctrl)
    
    base.makeIdentity(L_wrist_ctrl, apply = True, t = 1, r = 1, s = 1)
    base.parent(L_wrist_ctrl, "MASTER_CONTROLLER")
    
    #right
    R_wrist_ctrl1 = base.circle(nr = (0,1,0), c = (0,0,0), radius = 1, degree = 1, s = 16, name = "CTRL_R_Wrist0")
    R_wrist_ctrl2 = base.circle(nr = (1,0,0), c = (0,0,0), radius = 1, degree = 1, s = 16, name = "CTRL_R_Wrist1")
    R_wrist_ctrl3 = base.circle(nr = (0,0,1), c = (0,0,0), radius = 1, degree = 1, s = 16, name = "CTRL_R_Wrist2")
    R_wrist_ctrl = base.group(em = True, name ="CTRL_R_Wrist")
    curves = [R_wrist_ctrl1,R_wrist_ctrl2, R_wrist_ctrl3]
    
    for cv in curves:
        r_crvShape = base.listRelatives(cv, shapes = True)
        base.parent(r_crvShape, R_wrist_ctrl, s = True, r = True)
        base.delete(cv)
    
    base.addAttr(shortName = "PV", longName = "Elbow_PV", attributeType = 'double', defaultValue = 0, minValue = -100, maxValue = 100, keyable = True)    
    base.scale(0.07, 0.07, 0.07, R_wrist_ctrl)
    
    r_wristPos = base.xform(base.ls("RIG_R_Wrist"), q = True, t = True, ws = True)
    r_wristRot = base.joint(base.ls("RIG_R_Wrist"), q = True, o = True)
    
    base.move(r_wristPos[0], r_wristPos[1], r_wristPos[2], R_wrist_ctrl)
    base.rotate(0, 0, r_wristRot[0], R_wrist_ctrl)
    
    base.makeIdentity(R_wrist_ctrl, apply = True, t = 1, r = 1, s = 1)
    base.parent(R_wrist_ctrl, "MASTER_CONTROLLER")
Пример #38
0
def orientToMesh(mesh,
                 transform,
                 upVector=(0, 1, 0),
                 upVectorObject='',
                 normalAxis='x',
                 upAxis='y'):
    '''
	Orient a transform to the closest point on a specified mesh
	@param mesh: Mesh to orient to
	@type mesh: str
	@param transform: Transform to orient to mesh
	@type transform: str
	@param upVector: UpVector for rotation calculation
	@type upVector: tuple
	@param upVectorObject: UpVector will be calculated in the local space of this object
	@type upVectorObject: str
	@param normalAxis: Transform axis that will be aligned to the mesh normal
	@type normalAxis: str
	@param upAxis: Transform axis that will be aligned to the upVector
	@type upAxis: str
	'''
    # Check mesh
    if not isMesh(mesh):
        raise Exception('Object ' + mesh + ' is not a valid mesh!')
    # Get transform position
    pos = mc.xform(transform, q=True, ws=True, rp=True)
    # Get closest point on mesh
    mPos = closestPoint(mesh, pos)
    # Get closest normal
    norm = closestNormal(mesh, pos)

    # Check upVector object
    if upVectorObject:
        if not mc.objExists(upVectorObject):
            raise Exception('UpVector object "' + upVectorObject +
                            '" does not exist!!')
        upVectorMat = glTools.utils.matrix.buildMatrix(
            transform=upVectorObject)
        upVector = glTools.utils.matrix.vectorMatrixMultiply(
            upVector, upVectorMat, transformAsPoint=False, invertMatrix=False)

    # Build rotation matrix
    rotateOrder = mc.getAttr(transform + '.ro')
    mat = glTools.utils.matrix.buildRotation(norm, upVector, normalAxis,
                                             upAxis)
    rot = glTools.utils.matrix.getRotation(mat, rotateOrder)

    # Orient object to mesh
    mc.rotate(rot[0], rot[1], rot[2], transform, a=True, ws=True)
Пример #39
0
def createTargetPrim(*args):
    #delete existing target primitive
    #deleteTargetPrim()

    createTargetPrim.targetprim = 0

    if UI.targetPrim == 'Cube':
        createTargetPrim.targetprim = mc.polyCube(sx=1, sy=1, sz=1)
        mc.hyperShade(assign=Materials.shader)
        #mc.polyColorPerVertex( rgb=(UI.targetR, UI.targetG, UI.targetB), cdo = True )
        #if UI.randomOrientation != False:
        #mc.select(targetprim)
        mc.rotate(UI.targetOrientation[0],
                  UI.targetOrientation[1],
                  UI.targetOrientation[2],
                  a=True)

        if UI.targetMiddle != True:
            mc.move(random.randint(-10, 10), random.randint(-10, 10), 35)
        else:
            mc.move(0, 0, 35)

    if UI.targetPrim == 'Sphere':
        mc.polySphere(sx=24, sy=24, r=1)
        mc.hyperShade(assign=Materials.shader)
        #mc.polyColorPerVertex( rgb=(UI.targetR, UI.targetG, UI.targetB), cdo = True )
        if UI.targetMiddle != True:
            mc.move(random.randint(-10, 10), random.randint(-10, 10), 35)

    if UI.targetPrim == 'Cylinder':
        mc.polyCylinder(sx=24, sy=2, sz=2)
        mc.hyperShade(assign=Materials.shader)
        #mc.polyColorPerVertex( rgb=(UI.targetR, UI.targetG, UI.targetB), cdo = True )
        if UI.targetMiddle != True:
            mc.move(random.randint(-10, 10), random.randint(-10, 10), 35)

    if UI.targetPrim == 'Torus':
        mc.polyTorus(n='target', sx=24, sy=16, r=2, sr=1)
        mc.hyperShade(assign=Materials.shader)
        #mc.polyColorPerVertex( rgb=(UI.targetR, UI.targetG, UI.targetB), cdo = True )
        if UI.targetMiddle != True:
            mc.move(random.randint(-10, 10), random.randint(-10, 10), 35)

    if UI.targetPrim == 'Cone':
        mc.polyCone(sx=1, sy=1, sz=1)
        mc.hyperShade(assign=Materials.shader)
        #mc.polyColorPerVertex( rgb=(UI.targetR, UI.targetG, UI.targetB), cdo = True )
        if UI.targetMiddle != True:
            mc.move(random.randint(-10, 10), random.randint(-10, 10), 35)
Пример #40
0
 def instantiateRempartCurveBased(self, curveRampartName):
     #Step 1 : Create the curve of the shape
     self.curve = cmds.circle(s=self.resolution,
                              sw=360 - self.apertureAngle,
                              d=1,
                              r=self.radius,
                              n=curveRampartName)
     self.curveName = self.curve[0]
     cmds.rotate(90, -self.apertureAngle / 2, 0, self.curveName)
     #Step 2 : Create locators
     cmds.spaceLocator(p=cmds.pointPosition(self.curveName + '.cv[0]'))
     cmds.spaceLocator(p=cmds.pointPosition(self.curveName + '.cv[' +
                                            str(self.resolution) + ']'))
     #Step 3 : Create walls
     self.createSegmentsWalls()
    def testExportedNURBS(self):
        self._StartTest('nurbsCircleExport')

        cmds.move(6, -6, 6, 'persp')
        cmds.rotate(60, 0, 45, 'persp')
        cmds.modelEditor('modelPanel4', edit=True, grid=False)

        selection = ufe.Selection()
        selection.append(
            self._GetSceneItem('|stage|stageShape', '/nurbsCircle1'))

        self._RunTest(0, selection)
        self._RunTest(1, selection)
        self._RunTest(2, selection)
        self._RunTest(3, selection)
Пример #42
0
 def move(self, position=None, rotation=None):
     '''
     move the cursor object to position of point type
     '''
     if (not position):
         #reseting current position to previously stored position if any
         if (self.position):
             moveTo(self.cursorDAG, self.position)
             if (rotation):
                 mc.rotate(self.rotationIncrement[0], self.rotationIncrement[1], self.rotationIncrement[2], self.cursorDAG, os=True, r=True, rotateXYZ=True)
     else:
         self.position = position
         moveTo(self.cursorDAG, position)
         if (rotation):
             mc.rotate(self.rotationIncrement[0], self.rotationIncrement[1], self.rotationIncrement[2], self.cursorDAG, os=True, r=True, rotateXYZ=True)
Пример #43
0
    def setup(self):
        super(Finger, self).setup()
        #shrink the guides for the fingers. I mean really... Shrink them!

        for i in self.guides:
            cmds.select(i.getName())
            cmds.scale(0.2, 0.2, 0.2, r=True)

        #move the upv
        self.fkChainUpv.setPosition((2, 2, 0))
        #rotate and scale the masterGuides to look more appropriate
        cmds.select("{0}.cv[*]".format(self.masterGuide.getName()))
        cmds.rotate(90, 0, 0, r=True)
        cmds.scale(0.9, 0.9, 0.9, r=True)
        cmds.select(cl=True)
Пример #44
0
def MakeRailPiece(curve="", height=1.0, width=1.0):
    pos = mc.pointOnCurve(curve, pr=0, top=True)
    tan = mc.pointOnCurve(curve, pr=0, t=True, top=True)
    rot = math.degrees(math.atan2(tan[0], tan[2]))
    railPiece = mc.polyPlane(w=width, h=height, sx=1, sy=1)
    mc.move(pos[0], pos[1], pos[2])
    mc.rotate(90, rot, 0)
    mc.select(railPiece[0] + '.f[0]', leftCurve[0])
    div = distSleepers * 4
    mc.polyExtrudeFacet(railPiece[0] + '.f[0]',
                        inputCurve=curve,
                        divisions=div)
    mc.delete(railPiece[0], constructionHistory=True)

    return railPiece[0]
Пример #45
0
def rotate_offset(x, y, z, approach):
    """Rotate the current select to a position

    Args:
        x (int, float): value to move along x axis
        y (int, float): value to move along y axis
        z (int, float): value to move along z axis
        approach (str): method in which the action will take place, eg: relative

    Returns:
        None

    """
    selection = cmds.ls(selection=True, type="transform")
    cmds.rotate(selection, x, y, z, **{approach: True})
Пример #46
0
 def K_Frame(self):
     #K帧前,选择相机
     cmds.select(CameraName,r=True)
     global i
     i=1
     #移动相机的变换中心到网格中心
     cmds.move(0,0,0,CameraName+'.scalePivot',CameraName+'.rotatePivot',rpr=True)
     #移动时间滑块同时变换相机位置
     while i<=10:
         cmds.currentTime(5*i)
         i=i+1
         #每移动一次时间滑块,让相机沿Y旋转36°,旋转10次
         cmds.rotate(0,'36deg',0,r=True,os=True,fo=False,)
         #K帧
         cmds.setKeyframe()
Пример #47
0
def adjustRot(option):
    sel = getSelection()

    incremental = 10
    for each in sel:
        curr = cm.getAttr(each + ".ry")

        if option == "<":
            randVal = curr - incremental
        elif option == ">":
            randVal = curr + incremental
        else:
            randVal = rand.uniform(-180, 180)

        cm.rotate(0, randVal, 0, each)
Пример #48
0
    def runMultiSelectTestRotate(self, items, expected):
        '''Engine method to run multiple selection rotate test.'''

        # Save the initial positions to the memento list.
        self.multiSelectSnapShotAndTest(items, expected)

        # Do some rotate commands, and compare with expected. 
        for x, y, z in [[10, 20, 30], [-30, -20, -10]]:
            cmds.rotate(x, y, z, relative=True, objectSpace=True, forceOrderXYZ=True) # Just as in default rotations by manipulator
            expected = multiSelectAddRotations(expected, om.MEulerRotation(radians(x), radians(y), radians(z)))
            self.multiSelectSnapShotAndTest(items, expected)

        # Test undo, redo.
        self.multiSelectRewindMemento(items)
        self.multiSelectFforwardMemento(items)
Пример #49
0
    def mirrorFacialXform(self, jm, axis='x', debug=0):
        mirror = self.findMirrorJointMoverByName(jm)
        if debug:
            print mirror
        if mirror:
            pos = cmds.xform(jm, q=1, ws=1, rp=1)
            rot = cmds.xform(jm, q=1, ws=1, ro=1)
            #scale = cmds.xform(jm, q=1, r=1, s=1)

            cmds.select(mirror)
            if axis == 'x':
                cmds.move(-pos[0], pos[1], pos[2], mirror,  ws=1, rpr=1 )
                cmds.rotate(rot[0], -rot[1], -rot[2], mirror,  ws=1, a=1 )
            else:
                cmds.warning('Currently works for faces created looking down y axis.')
Пример #50
0
def getWristToWorldRotation( wrist, performRotate=False ):
	'''
	'''
	basis = map(api.MVectorToVector, api.getBases( wrist ))
	rots = [0, 0, 0]
	for n, axis in enumerate( AXES[:3] ):
		axis = Vector.Axis( axis )
		if axis.dot( basis[n] ) < 0:
			rots[n] = 180

	if performRotate:
		rots.append( wrist )
		cmd.rotate(rots[0], rots[1], rots[2], wrist, a=True, ws=True)

	return tuple( rots )
Пример #51
0
def set_joint_orient(reset=True):
    from . import sisidebar_sub

    joints = cmds.ls(sl=True, type="joint")

    if len(joints) == 0:
        confirm_mes = lang.Lang(
            en=
            "Joint is not selected\nDo you want to process all the joints in the scene? ",
            ja="ジョイントが選択されていません\nシーン内のすべてのジョイントを処理しますか?",
        )
        rtn = pm.cmds.confirmDialog(
            title="Confirm",
            message=confirm_mes.output(),
            button=["Yes", "No"],
            defaultButton="Yes",
            cancelButton="No",
            dismissString="No",
        )
        if rtn != "Yes":
            return False

        joints = cmds.ls("*", type="joint")
        if len(joints) == 0:
            pm.confirmDialog(
                title="Warning",
                message="Joint Object Nothing.",
                button="OK",
                icon="Warning",
            )
            return False

    for j in joints:
        # マトリックス取得
        mat = cmds.xform(j, q=True, m=True)
        # 回転とジョイントの方向をいったん0に
        cmds.rotate(0, 0, 0, j, objectSpace=True)
        cmds.joint(j, e=True, orientation=[0, 0, 0])
        # マトリックス再設定、回転のみに数値が入る。
        cmds.xform(j, m=mat)

        if reset:
            # 回転取得
            rot = cmds.xform(j, q=True, ro=True)
            # 回転を0にしてジョイントの方向に同じ値を移す
            cmds.rotate(0, 0, 0, j, objectSpace=True)
            cmds.joint(j, e=True, orientation=rot)
    sisidebar_sub.get_matrix()
Пример #52
0
    def createPetals(self):
        '''This method creates the petals of flower. '''

        # create the petal
        mc.sphere(ax=(0, 1, 0))
        mc.move(0, 0, -1.6)
        mc.scale(0.7, 0.3, 1.7)
        self.currentPetal = mc.ls(sl=True)
        currentPetal0 = self.currentPetal[0]

        # reset the coordinates
        mc.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
        mc.move(0, 0, 0, currentPetal0 + '.scalePivot')
        mc.move(0, 0, 0, currentPetal0 + '.rotatePivot')

        # move the tip of the petal
        mc.select(currentPetal0 + ".cv[3] [7]")
        mc.move(0, 1.5, 0, r=True)

        # select the inner part of the petal
        # move them down
        for uCV in range(5, 7):
            for vCV in range(0, 8):
                mc.select(currentPetal0 + ".cv[" + str(uCV) + "] [" +
                          str(vCV) + "]")
                mc.move(0, -0.3, 0, r=True)

        # delete history
        mc.select(currentPetal0)
        maya.mel.eval("DeleteHistory")

        # create the rest of the petals
        numPetals = random.randrange(10, 20)
        mc.select(currentPetal0)
        degreeApart = (360 / numPetals)
        for i in range(0, numPetals):
            newPetal = mc.duplicate(rr=True)
            self.currentPetal.append(newPetal)
            mc.rotate(0, degreeApart, 0, r=True)

            # randomly rotate the petals
            petalRX = random.randrange(-5, 5)
            petalRY = random.randrange(-5, 5)
            petalRZ = random.randrange(-5, 5)
            mc.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
            mc.rotate(petalRX, petalRY, petalRZ, r=True)

        return self.currentPetal
    def testSelection(self):
        cmds.file(force=True, new=True)
        mayaUtils.loadPlugin("mayaUsdPlugin")
        panel = mayaUtils.activeModelPanel()
        usdaFile = testUtils.getTestScene("setsCmd", "5prims.usda")
        proxyDagPath, sphereStage = mayaUtils.createProxyFromFile(usdaFile)

        cmds.move(-4, -24, 0, "persp")
        cmds.rotate(90, 0, 0, "persp")

        usdCube = proxyDagPath + ",/Cube1"
        usdCylinder = proxyDagPath + ",/Cylinder1"

        # Test smooth shaded
        cmds.modelEditor('modelPanel4',
                         e=True,
                         displayAppearance='smoothShaded',
                         displayLights='default')
        cmds.modelEditor('modelPanel4',
                         e=True,
                         wireframeOnShaded=False,
                         displayLights='default')
        self._selectionTest('', usdCube, usdCylinder, proxyDagPath,
                            'smoothShaded')

        # Test smooth shaded
        cmds.modelEditor('modelPanel4',
                         e=True,
                         displayAppearance='smoothShaded',
                         displayLights='default')
        cmds.modelEditor('modelPanel4',
                         e=True,
                         wireframeOnShaded=True,
                         displayLights='default')
        self._selectionTest('', usdCube, usdCylinder, proxyDagPath,
                            'wireframeOnShaded')

        # Test smooth shaded
        cmds.modelEditor('modelPanel4',
                         e=True,
                         displayAppearance='wireframe',
                         displayLights='default')
        cmds.modelEditor('modelPanel4',
                         e=True,
                         wireframeOnShaded=False,
                         displayLights='default')
        self._selectionTest('', usdCube, usdCylinder, proxyDagPath,
                            'wireframe')
    def testInstancedSelection(self):
        cmds.file(force=True, new=True)
        mayaUtils.loadPlugin("mayaUsdPlugin")
        panel = mayaUtils.activeModelPanel()
        usdaFile = testUtils.getTestScene("instances",
                                          "perInstanceInheritedData.usda")
        proxyDagPath, sphereStage = mayaUtils.createProxyFromFile(usdaFile)
        usdball01 = proxyDagPath + ",/root/group/ball_01"
        usdball03 = proxyDagPath + ",/root/group/ball_03"

        cmds.move(8.5, -20, 0, "persp")
        cmds.rotate(90, 0, 0, "persp")

        # Test smooth shaded
        cmds.modelEditor('modelPanel4',
                         e=True,
                         displayAppearance='smoothShaded',
                         displayLights='default')
        cmds.modelEditor('modelPanel4',
                         e=True,
                         wireframeOnShaded=False,
                         displayLights='default')
        self._selectionTest('instance_', usdball01, usdball03, proxyDagPath,
                            'smoothShaded')

        # Test smooth shaded
        cmds.modelEditor('modelPanel4',
                         e=True,
                         displayAppearance='smoothShaded',
                         displayLights='default')
        cmds.modelEditor('modelPanel4',
                         e=True,
                         wireframeOnShaded=True,
                         displayLights='default')
        self._selectionTest('instance_', usdball01, usdball03, proxyDagPath,
                            'wireframeOnShaded')

        # Test smooth shaded
        cmds.modelEditor('modelPanel4',
                         e=True,
                         displayAppearance='wireframe',
                         displayLights='default')
        cmds.modelEditor('modelPanel4',
                         e=True,
                         wireframeOnShaded=False,
                         displayLights='default')
        self._selectionTest('instance_', usdball01, usdball03, proxyDagPath,
                            'wireframe')
Пример #55
0
def moveOrientSnap(obj, target):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Snaps with a orient constraint style
    
    ARGUMENTS:
    obj(string)
    target(string)
    
    RETURNS:
    Nothin
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    objRot = mc.xform(target, q=True, ws=True, ro=True)
    mc.rotate(objRot[0], objRot[1], objRot[2], [obj], ws=True)
Пример #56
0
def revolve(iterations):
    if iterations == 1:
        print("stop")
    else:
        cmds.select()
        cmds.duplicate()
        cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
        cmds.move(posX,
                  posY,
                  posZ,
                  ".scalePivot",
                  ".rotatePivot",
                  absolute=True)
        cmds.rotate(0, angle, 0)
        print("iteration = ", str(iterations))
        revolve(iterations - 1)
Пример #57
0
def lockEye(*arg):
    #print 'lock'
    selectobj = maya.ls(sl=True)
    for obj in selectobj:
        if obj == 'cc_l_eyeball01' or obj == 'cc_r_eyeball01':
            pos = maya.xform(obj, q=True, t=True, ws=True)
            rot = maya.xform(obj, q=True, ro=True, ws=True)
            maya.setAttr(obj + '.EyepositionLock', 1)
            print pos
            print rot
            maya.move(pos[0], pos[1], pos[2], obj, a=True, ws=True)
            maya.rotate(rot[0], rot[1], rot[2], obj, a=True, ws=True)
        else:
            maya.warning(
                'please select "cc_r_eyeball01" or "cc_r_eyeball01" to lock the control'
            )
def randomRotator(objectName):
    startTime = cmds.playbackOptions(query=True, minTime=True)
    endTime = cmds.playbackOptions(query=True, maxTime=True)
    for objects in getSpecificObjectsIntoArray(objectName):
        rN = rand.uniform(40, 80)
        print rN
        cmds.rotate(30, rN, 50, objects, a=True)
        cmds.cutKey(objectName, time=(startTime, endTime), attribute='rotateY')
        cmds.setKeyframe(objectName,
                         time=startTime,
                         attribute='rotateY',
                         value=0)
        cmds.setKeyframe(objectName,
                         time=endTime,
                         attribute='rotateY',
                         value=360)
Пример #59
0
def SetupLighting():
    #creation lumiere ambiante
    mutils.createLocator("aiAreaLight", asLight=True)
    lum1 = cmds.rename("LumiereAmbiante")
    cmds.rotate(-90, 0, 0)
    cmds.move(0, 17, 0)
    cmds.scale(15, 15, 15)
    cmds.setAttr(lum1 + ".color", 0, 0.19, 1)
    cmds.setAttr(lum1 + ".intensity", 79)
    #creation lumiere centrale
    mutils.createLocator("aiAreaLight", asLight=True)
    lum2 = cmds.rename("LumiereCentale")
    cmds.rotate(-205, 75, -140)
    cmds.move(5, 8, -3)
    cmds.setAttr(lum2 + ".color", 1, 0.66, 0.44)
    cmds.setAttr(lum2 + ".intensity", 100)
Пример #60
0
    def create_finger_locators(self):
        """
        Creates the locators for the finger position alignments.

        Args:
            side (str): Body orientation of the fingers.
                'L/M/R' are appropriate inputs.

        """
        self.hand_parent = cmds.spaceLocator(
            name='Hand_{side}_handBase_POS'.format(side=self.side))[0]
        for finger, segments in self.fingers_dict.iteritems():
            for segment in segments:
                cmds.spaceLocator(name='{segment}_POS'.format(side=self.side,
                                                              segment=segment))
            # Parenting logic
            for loc in range(len(segments)):
                if loc == (len(segments) - 1):
                    cmds.parent(segments[0] + '_POS', self.hand_parent)
                else:
                    cmds.parent(segments[loc + 1] + '_POS',
                                segments[loc] + '_POS')

        cmds.setAttr(self.hand_parent + '.overrideEnabled', 1)
        cmds.setAttr(self.hand_parent + '.overrideColor', 13)

        i = (len(self.fingers_dict) / 2) - 1
        for key in sorted(self.fingers_dict.keys()):
            for segment in self.fingers_dict[key]:
                cmds.move(1, 0, 0, segment + '_POS', relative=True)
            cmds.move(1,
                      0,
                      i,
                      self.fingers_dict[key][0] + '_POS',
                      relative=True)
            if 'thumb' in key:
                cmds.rotate(0,
                            -45,
                            0,
                            self.fingers_dict[key][0] + '_POS',
                            relative=True)
                cmds.move(-1,
                          0,
                          len(self.fingers_dict),
                          self.fingers_dict[key][0] + '_POS',
                          relative=True)
            i -= 1