コード例 #1
0
def ldmt_pfxToCurves():
    if cmds.currentCtx() == 'dynWireCtx1':
        new = cmds.ls(sl=True)
        if not new:
            return
        whichNode = cmds.ls(cmds.listRelatives(new, s=True)[0], st=True)[1]
        if whichNode == 'stroke':
            newStroke = new[0]
            cmds.select(newStroke, r=True)
            #            return
            mel.eval('doPaintEffectsToCurve(1);')
            st = cmds.listRelatives(newStroke, s=True)[0]
            c = cmds.listConnections(st, et=True, t='nurbsCurve')[0]
            cmds.rebuildCurve(c,
                              ch=1,
                              rpo=1,
                              rt=0,
                              end=1,
                              kr=0,
                              kcp=0,
                              kep=1,
                              kt=0,
                              s=10,
                              d=3,
                              tol=0.01)
            cmds.select(cl=True)
            strokeMainCurves = cmds.listRelatives(c, ap=1)
            strokeCurve = cmds.listRelatives(strokeMainCurves, ap=1)
            cmds.ungroup(strokeCurve)
            cmds.ungroup(strokeMainCurves)
            cmds.evalDeferred('cmds.delete("' + newStroke + '")')
コード例 #2
0
def ctrl_text(var):
	"""
	Creates letters and text made from multipe curves.
	"""
	cmds.textCurves(ch=0, f='Times New Roman', t=var)
	cmds.ungroup()
	cmds.ungroup()
	print 'Curves have been ungrouped.'
	
	curves = cmds.ls(sl=True)
	cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
	print 'Freezing transforms on curves.'
	
	cmds.pickWalk(d='Down')
	shapes = cmds.ls(sl=True)
	print 'Creating a list of curve shape nodes.'
	
	
	parent_shapes = shapes[1:]
	delete_curves = curves[1:]
	print 'Slicing lists for parenting and deleting purposes.'
	
	cmds.select(parent_shapes, r=True)
	cmds.select(curves[0], add=True)
	cmds.parent(r=True, s=True)
	print 'Curve list has been parented into single curve.'
	
	cmds.select(delete_curves, r=True)
	mel.eval('doDelete')
	print 'Unused groups have been deleted.'
	
	cmds.select(curves[0])
	mel.eval('CenterPivot')
	print ('End result curve have been selected and its pivot has been centered.')
コード例 #3
0
def ctrl_text(var):
    """
	Creates letters and text made from multipe curves.
	"""
    cmds.textCurves(ch=0, f='Times New Roman', t=var)
    cmds.ungroup()
    cmds.ungroup()
    print 'Curves have been ungrouped.'

    curves = cmds.ls(sl=True)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    print 'Freezing transforms on curves.'

    cmds.pickWalk(d='Down')
    shapes = cmds.ls(sl=True)
    print 'Creating a list of curve shape nodes.'

    parent_shapes = shapes[1:]
    delete_curves = curves[1:]
    print 'Slicing lists for parenting and deleting purposes.'

    cmds.select(parent_shapes, r=True)
    cmds.select(curves[0], add=True)
    cmds.parent(r=True, s=True)
    print 'Curve list has been parented into single curve.'

    cmds.select(delete_curves, r=True)
    mel.eval('doDelete')
    print 'Unused groups have been deleted.'

    cmds.select(curves[0])
    mel.eval('CenterPivot')
    print(
        'End result curve have been selected and its pivot has been centered.')
コード例 #4
0
    def reversePath_button(self, a):

        self.dupCam_Name = mc.duplicate(
            self.selCam_Name
        )  ### Duplicate Render Camera / Just for constraint uses...
        mc.duplicate(self.selObject_Name)  ### Duplicate Object

        mc.group(self.selCam_Name,
                 name=self.reversePathGrp)  ### Group Render Cam

        mc.parent(self.reversePathGrp,
                  self.selObject_Name)  ### Parent reversePathGrp to Object

        self.pointConstraintName = mc.pointConstraint(self.dupCam_Name,
                                                      self.selCam_Name,
                                                      maintainOffset=False)
        self.orientConstraintName = mc.orientConstraint(self.dupCam_Name,
                                                        self.selCam_Name,
                                                        maintainOffset=False)

        mc.bakeResults(self.selCam_Name,
                       time=(self.startTime, self.endTime),
                       at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
        mc.delete(self.pointConstraintName)
        mc.delete(self.orientConstraintName)

        mc.ungroup(self.reversePathGrp, world=True)

        mc.hide(self.selObject_Name)
        mc.hide(self.dupCam_Name)
        return
コード例 #5
0
ファイル: JR_tool_class.py プロジェクト: jricker/JR_Maya
 def chipFacesTool(self):
     # cuts faces off of the poly and then seperates the faces to it's own polygon object, also ungroups them
     selectedFaces = self.getSelection()
     selectionParent = cmds.listRelatives(selectedFaces[0], p=True)
     cmds.polyChipOff(selectedFaces, dup=True)
     seperated = cmds.polySeparate(selectionParent[0])
     allSeperated = [i for i in seperated if 'Separate' not in i]
     if len(allSeperated) > 2:
         cmds.polyUnite(allSeperated[1:])
         new = self.getSelection()
     else:
         new = allSeperated[1]
     old = []
     old.append(allSeperated[0])
     oldParent = cmds.listRelatives(old[0], p=True)
     oldParentChildren = cmds.listRelatives(oldParent[0], c=True)
     oldNodesToDelete = set(old) ^ set(oldParentChildren)
     print oldNodesToDelete, ' this is old nodes to delete'
     cmds.ungroup(oldParent)
     cmds.delete(new, ch=1)
     cmds.delete(old, ch=1)
     cmds.rename(old, oldParent)
     cmds.select(new)
     self.assignRandomMaterial(
     )  # assigns random lambert to newly created poly
     cmds.delete(selectedFaces)
     cmds.select(old)
     cmds.xform(centerPivots=True)
     cmds.select(new)  # reselect it after material assign
     cmds.xform(centerPivots=True)  # Center pivot of new article.
     JR_rename_tool.UI('exit')  # to rename the freshly branched poly
コード例 #6
0
ファイル: JR_tool_class.py プロジェクト: jricker/JR_Maya
	def chipFacesTool(self):
		# cuts faces off of the poly and then seperates the faces to it's own polygon object, also ungroups them
		selectedFaces = self.getSelection()
		selectionParent = cmds.listRelatives(selectedFaces[0], p=True)
		cmds.polyChipOff( selectedFaces, dup=True)
		seperated = cmds.polySeparate(selectionParent[0])
		allSeperated = [i for i in seperated if 'Separate' not in i]
		if len(allSeperated) > 2:
			cmds.polyUnite(allSeperated[1:])
			new = self.getSelection()
		else:
			new = allSeperated[1]
		old = []; old.append(allSeperated[0])
		oldParent = cmds.listRelatives(old[0], p=True)
		oldParentChildren = cmds.listRelatives(oldParent[0], c=True)
		oldNodesToDelete = set(old) ^ set(oldParentChildren)
		print oldNodesToDelete, ' this is old nodes to delete'
		cmds.ungroup( oldParent )
		cmds.delete(new, ch=1)
		cmds.delete(old, ch=1)
		cmds.rename(old, oldParent )
		cmds.select(new)
		self.assignRandomMaterial() # assigns random lambert to newly created poly
		cmds.delete(selectedFaces)
		cmds.select(old)
		cmds.xform(centerPivots = True)
		cmds.select(new) # reselect it after material assign
		cmds.xform(centerPivots = True) # Center pivot of new article.
		JR_rename_tool.UI('exit') # to rename the freshly branched poly
コード例 #7
0
ファイル: testUngroupCmd.py プロジェクト: mattyjams/maya-usd
    def testUngroupMultipleGroupItems(self):
        '''Verify ungrouping of multiple group nodes.'''

        sphereGen = SphereGenerator(2, self.contextOp, self.proxyShapePathStr)

        sphere1Path = sphereGen.createSphere()
        sphere2Path = sphereGen.createSphere()

        # create group1
        cmds.group(ufe.PathString.string(sphere1Path))

        # create group2
        cmds.group(ufe.PathString.string(sphere2Path))

        self.assertEqual([x for x in self.stage.Traverse()], [
            self.stage.GetPrimAtPath("/group1"),
            self.stage.GetPrimAtPath("/group1/Sphere1"),
            self.stage.GetPrimAtPath("/group2"),
            self.stage.GetPrimAtPath("/group2/Sphere2")
        ])

        # ungroup
        cmds.ungroup("{},/group1".format(self.proxyShapePathStr),
                     "{},/group2".format(self.proxyShapePathStr))

        self.assertEqual([x for x in self.stage.Traverse()], [
            self.stage.GetPrimAtPath("/Sphere1"),
            self.stage.GetPrimAtPath("/Sphere2")
        ])
コード例 #8
0
def MirrorBojs():

    slc = cmds.ls(sl=True)

    if (len(slc) == 0):
        cmds.inViewMessage(amg='Please select something to <hl>Mirror</hl>.',
                           pos='botCenter',
                           fade=True)

    else:

        newObj = cmds.duplicate(slc, n=('Mirrored_' + str(slc[0])))
        newobjgrp = cmds.group(newObj, n=(str(slc[0]) + '_MirrorGrp'))
        mel.eval("xform -os -piv 0 0 0;")
        cmds.scale(-1, 1, 1)
        cmds.ungroup(newobjgrp)
        cmds.makeIdentity(newObj, apply=True, t=1, r=1, s=1)
        cmds.select(newObj)
        a = cmds.promptDialog(title='Mirror',
                              message='If LT suffix exists type 1',
                              button=['Rename', "Don't Rename"],
                              defaultButton='Rename',
                              cancelButton="Don't Rename",
                              dismissString='Not Renaming')
        if a == 'Rename':

            text = cmds.promptDialog(query=True, text=True)
            g = int(text)

            try:
                mel.eval('searchReplaceNames"_LT" "_RT" "selected"')
            except:
                pass
            try:
                mel.eval('searchReplaceNames"_lt" "_rt" "selected"')

            except:
                pass

            try:
                mel.eval('searchReplaceNames"_L" "_R" "selected"')

            except:
                pass
            try:
                mel.eval('searchReplaceNames"_Left" "_Right" "selected"')

            except:
                pass

            if g == 1:
                mel.eval('searchReplaceNames"Mirrored_" "" "selected"')
                print 'removed mirrored names'

            else:
                pass

        else:
            pass
コード例 #9
0
ファイル: JR_tool_class.py プロジェクト: jricker/JR_Maya
	def polySeperateTool(self):
		cmds.polySeparate()
		cmds.delete(ch=1)
		A = self.getSelection()
		B = cmds.listRelatives(A[0], p=True)
		cmds.ungroup( B )
		cmds.select(A)
		JR_rename_tool.UI('exit') # to rename the freshly branched poly
コード例 #10
0
ファイル: JR_tool_class.py プロジェクト: jricker/JR_Maya
 def polySeperateTool(self):
     cmds.polySeparate()
     cmds.delete(ch=1)
     A = self.getSelection()
     B = cmds.listRelatives(A[0], p=True)
     cmds.ungroup(B)
     cmds.select(A)
     JR_rename_tool.UI('exit')  # to rename the freshly branched poly
コード例 #11
0
def ctrl_letter(var):
    """
	Creates letters made from single curves.
	"""
    cmds.textCurves(ch=0, f='Times New Roman', t=var)
    cmds.ungroup()
    cmds.ungroup()
    mel.eval('CenterPivot')
    print 'Curve has been selected and its pivot as been centered.'
コード例 #12
0
def ctrl_letter(var):
	"""
	Creates letters made from single curves.
	"""
	cmds.textCurves(ch=0, f='Times New Roman', t=var)
	cmds.ungroup()
	cmds.ungroup()
	mel.eval('CenterPivot')
	print 'Curve has been selected and its pivot as been centered.'
コード例 #13
0
def moveToOrigin():
    # group and move all geo to origin
    cmds.select(cmds.listRelatives(cmds.ls(geometry=True), p=True, path=True), r=True)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    cmds.group(n='tempGroup')
    bbox = cmds.exactWorldBoundingBox()
    bottom = [(bbox[0] + bbox[3])/2, bbox[1], (bbox[2] + bbox[5])/2]
    cmds.xform(piv=bottom, ws=True)
    cmds.move(rpr=True)
    cmds.ungroup('tempGroup')
コード例 #14
0
def stopBackflip():
    """stop backflip action and clean up group / keys """
    
    ms.cutKey('flipper')
    ms.play(st=False)
    ms.scale(1,1,1,'flipper')
    ms.rotate(0,0,0, 'flipper')
    ms.move(0,0,0, 'flipper')
    ms.ungroup('flipper')
    ms.currentTime(1)
コード例 #15
0
def moveToOrigin():
    # group and move all geo to origin
    cmds.select(cmds.listRelatives(cmds.ls(geometry=True), p=True, path=True),
                r=True)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    cmds.group(n='tempGroup')
    bbox = cmds.exactWorldBoundingBox()
    bottom = [(bbox[0] + bbox[3]) / 2, bbox[1], (bbox[2] + bbox[5]) / 2]
    cmds.xform(piv=bottom, ws=True)
    cmds.move(rpr=True)
    cmds.ungroup('tempGroup')
コード例 #16
0
ファイル: RigToolKit.py プロジェクト: romadave91/MyScripts
def MirrorControlObjects():
    sel_Obj = cmds.ls(sl=True)        					  #stores all the selected objects
    if len(sel_Obj)==0:                                   #if no object is selected : Throws a warning
        cmds.warning("select object")
    else:
        cmds.duplicate(rr=True)    						 #duplicates the object
        grp_sel_Obj = cmds.group()                       #groups the object
        cmds.xform(os=True,piv=[0,0,0])                  #centers the pivot point
        cmds.setAttr(grp_sel_Obj+".sx",-1)               #mirrors it across by setting scale.X to -1
        cmds.select(grp_sel_Obj)
        cmds.ungroup()                                   #ungroups the object
        cmds.makeIdentity(apply=True)    				 #freezes the transform
コード例 #17
0
ファイル: testUngroupCmd.py プロジェクト: mattyjams/maya-usd
    def testUngroupLeaf(self):
        '''Verify ungrouping of a leaf node.'''
        # create a sphere generator
        sphereGen = SphereGenerator(1, self.contextOp, self.proxyShapePathStr)

        # create a sphere
        sphere1Path = sphereGen.createSphere()

        # expect the exception happens
        with self.assertRaises(RuntimeError):
            # ungroup
            cmds.ungroup(ufe.PathString.string(sphere1Path))
コード例 #18
0
ファイル: testUngroupCmd.py プロジェクト: mattyjams/maya-usd
    def testUngroupWorld(self):
        '''Verify -world flag.'''

        # create a sphere generator
        sphereGen = SphereGenerator(4, self.contextOp, self.proxyShapePathStr)

        # create 4 spheres
        pathList = list()
        for _ in range(4):
            pathList.append(sphereGen.createSphere())

        # group /Sphere2, /Sphere3, /Sphere4
        cmds.group(ufe.PathString.string(pathList[1]),
                   ufe.PathString.string(pathList[2]),
                   ufe.PathString.string(pathList[3]))

        # verify the paths after grouping
        self.assertEqual([x for x in self.stage.Traverse()], [
            self.stage.GetPrimAtPath("/Sphere1"),
            self.stage.GetPrimAtPath("/group1"),
            self.stage.GetPrimAtPath("/group1/Sphere2"),
            self.stage.GetPrimAtPath("/group1/Sphere3"),
            self.stage.GetPrimAtPath("/group1/Sphere4")
        ])

        # group /group1/Sphere2, /group1/Sphere3, /group1/Sphere4
        cmds.group("{},/group1/Sphere2".format(self.proxyShapePathStr),
                   "{},/group1/Sphere3".format(self.proxyShapePathStr),
                   "{},/group1/Sphere4".format(self.proxyShapePathStr))

        # verify the paths after second grouping
        self.assertEqual([x for x in self.stage.Traverse()], [
            self.stage.GetPrimAtPath("/Sphere1"),
            self.stage.GetPrimAtPath("/group1"),
            self.stage.GetPrimAtPath("/group1/group1"),
            self.stage.GetPrimAtPath("/group1/group1/Sphere2"),
            self.stage.GetPrimAtPath("/group1/group1/Sphere3"),
            self.stage.GetPrimAtPath("/group1/group1/Sphere4")
        ])

        # remove /group1/group1 from the hierarchy with the -world flag
        cmds.ungroup("{},/group1/group1".format(self.proxyShapePathStr),
                     world=True)

        # verify the paths after ungroup
        self.assertEqual([x for x in self.stage.Traverse()], [
            self.stage.GetPrimAtPath("/Sphere1"),
            self.stage.GetPrimAtPath("/group1"),
            self.stage.GetPrimAtPath("/Sphere2"),
            self.stage.GetPrimAtPath("/Sphere3"),
            self.stage.GetPrimAtPath("/Sphere4")
        ])
コード例 #19
0
def nm_alignLRAs():
	sel = []
	sel = cmds.ls( sl = True )
	ctrl = sel[0]
	joint = sel[1]
	
	rememberPad = cmds.group( ctrl, n = ctrl + '_rememberPad' )
	orientPad = cmds.createNode( 'transform', n = ctrl + '_orientPad' ) 
	cmds.delete( cmds.parentConstraint( joint, orientPad ) )
	cmds.parent( orientPad, rememberPad )
	cmds.parent( ctrl, orientPad )
	cmds.makeIdentity( ctrl, a = True, t = 1, r = 1, n = 0)
	cmds.ungroup( rememberPad )
コード例 #20
0
def nm_alignLRAs():
    sel = []
    sel = cmds.ls(sl=True)
    ctrl = sel[0]
    joint = sel[1]

    rememberPad = cmds.group(ctrl, n=ctrl + '_rememberPad')
    orientPad = cmds.createNode('transform', n=ctrl + '_orientPad')
    cmds.delete(cmds.parentConstraint(joint, orientPad))
    cmds.parent(orientPad, rememberPad)
    cmds.parent(ctrl, orientPad)
    cmds.makeIdentity(ctrl, a=True, t=1, r=1, n=0)
    cmds.ungroup(rememberPad)
コード例 #21
0
ファイル: testUngroupCmd.py プロジェクト: mattyjams/maya-usd
    def testUngroupProxyShape(self):
        '''Verify ungrouping of the proxyShape results in error.'''

        # create a sphere generator
        sphereGen = SphereGenerator(5, self.contextOp, self.proxyShapePathStr)

        # create 5 spheres
        for _ in range(5):
            sphereGen.createSphere()

        # ungrouping the proxy shape with existing USD children should fail
        with self.assertRaises(RuntimeError):
            cmds.ungroup(ufe.PathString.string(self.proxyShapeItem.path()))
コード例 #22
0
def unGroup(args):

    sel = mc.ls(sl=1)

    try:
        if sel:
            mc.ungroup(sel, w=1)

            printDONE('Ungrop Done.')

        else:
            printWAR('select some group')
    except:
        printWAR('This dont group')
コード例 #23
0
 def __init__(self):
     selectedObjects = cmds.ls(sl=True, transforms=True)
     
     filteredGroups = []   
     for obj in selectedObjects:
         if obj.find("Group__") == 0:
             filteredGroups.append(obj) 
             
     if len(filteredGroups) == 0:
         return
     
     groupContainer = "Group_container"
     modules = []
     for group in filteredGroups:
         modules.extend(self.findChildModules(group))
         
     moduleContainers = [groupContainer]
     for module in modules:
         moduleContainer = module + ":module_container"
         moduleContainers.append(moduleContainer)
         
     for container in moduleContainers:
         cmds.lockNode(container, lock=False, lockUnpublished=False)
         
     for group in filteredGroups:
         numChildren = len(cmds.listRelatives(group, children=True))
         # Ungroup childeren from group
         if numChildren > 1:
             cmds.ungroup(group, absolute=True)
         # Remove attrs from container    
         for attr in ["t", "r", "globalScale"]:
             cmds.container(groupContainer, edit=True, unbindAndUnpublish=group+"."+attr)
             
         parentGroup = cmds.listRelatives(group, parent=True)
             
         cmds.delete(group)
         # This will ensure that if a module is deleted, we do not leave an empty group
         if parentGroup != None:
             parentGroup = parentGroup[0]
             children = cmds. listRelatives(parentGroup, children=True)
             children = cmds.ls(children, transforms=True)
             
             if len(children) == 0:
                 cmds.select(parentGroup, replace=True)
                 UngroupSelected()
                 
     # Lock containers
     for container in moduleContainers:
         if cmds.objExists(container):
             cmds.lockNode(container, lock=True, lockUnpublished=True)
コード例 #24
0
	def __init__(self):
		selectedObjects = cmds.ls(selection=True, transforms=True)
		
		filteredGroups = []
		for obj in selectedObjects:
			if obj.find('Group__') == 0:
				filteredGroups.append(obj)
				
		if len(filteredGroups) == 0:
			return
			
		groupContainer = 'Group_container'
		modules = []
		for group in filteredGroups:
			modules.extend(self.findChildModules(group))
			
		moduleContainers = [groupContainer]
		for module in modules:
			moduleContainer = (module + ':module_container')
			moduleContainers.append(moduleContainer)
			
		for container in moduleContainers:
			cmds.lockNode(container, lock=False, lockUnpublished=False)
			
		for group in filteredGroups:
			numberOfChildren = len(cmds.listRelatives(group, children=True))
			if numberOfChildren > 1:
				cmds.ungroup(group, absolute=True)
				
			for attr in ['t', 'r', 'globalScale']:
				cmds.container(groupContainer, edit=True,unbindAndUnpublish=(group + '.' + attr))
				
			parentGroup = cmds.listRelatives(group,parent=True)
			
				
			cmds.delete(group)
			
			if parentGroup != None:
				parentGroup = parentGroup[0]
				children = cmds.listRelatives(parentGroup, children=True)
				children = cmds.ls(children, transforms=True)
				
				if len(children) == 0:
					cmds.select(parentGroup, replace=True)
					UngroupSelected()
					
		for container in moduleContainers:
			if cmds.objExists(container):
				cmds.lockNode(container, lock=True, lockUnpublished=True)
コード例 #25
0
def create_text(text):
    cmds.textCurves(ch=0, t=text)
    print(text)
    cmds.ungroup()
    cmds.ungroup()
    curves = cmds.ls(sl=True)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    shapes = curves[1:]
    cmds.select(shapes, r=True)
    cmds.pickWalk(d='Down')
    cmds.select(curves[0], tgl=True)
    cmds.parent(r=True, s=True)
    cmds.pickWalk(d='up')
    cmds.delete(shapes)
    cmds.xform(cp=True)
    return cmds.ls(sl=True)[0]
コード例 #26
0
ファイル: testUngroupCmd.py プロジェクト: mattyjams/maya-usd
    def testUngroupAbsolute(self):
        '''Verify -absolute flag.'''

        # create a sphere generator
        sphereGen = SphereGenerator(2, self.contextOp, self.proxyShapePathStr)

        # create a sphere and move it on x axis by +2
        sphere1Path = sphereGen.createSphere()
        sphere1T3d = createTransform3d(sphere1Path)
        sphere1T3d.translate(2.0, 0.0, 0.0)

        # create another sphere and move it on x axis by -2
        sphere2Path = sphereGen.createSphere()
        sphere2T3d = createTransform3d(sphere2Path)
        sphere2T3d.translate(-2.0, 0.0, 0.0)

        # create a group
        groupName = cmds.group(ufe.PathString.string(sphere1Path),
                               ufe.PathString.string(sphere2Path))

        # move the group
        cmds.move(7.0, 8.0, 12.0, r=True)

        # verify selected item is "group1"
        self.assertEqual(len(self.globalSn), 1)
        groupItem = self.globalSn.front()

        if ufe.VersionInfo.getPatchLevel() >= 1:
            self.assertEqual(groupItem.nodeName(), groupName)
        else:
            self.assertEqual(groupItem.nodeName(), "group1")

        # remove group1 from the hierarchy. What should remain
        # is /Sphere1, /Sphere2.
        cmds.ungroup("{},/group1".format(self.proxyShapePathStr))

        # the objects don't move since the `absolute` flag is implied by default.
        spherePrim = mayaUsd.ufe.ufePathToPrim(
            ufe.PathString.string(sphere1Path))
        translateAttr = spherePrim.GetAttribute('xformOp:translate')
        self.assertEqual(translateAttr.Get(), Gf.Vec3d(9.0, 8.0, 12.0))

        spherePrim = mayaUsd.ufe.ufePathToPrim(
            ufe.PathString.string(sphere2Path))
        translateAttr = spherePrim.GetAttribute('xformOp:translate')
        self.assertEqual(translateAttr.Get(), Gf.Vec3d(5.0, 8.0, 12.0))
コード例 #27
0
ファイル: divineJoint.py プロジェクト: mappp7/tools
def divineJoint():
    locList = cmds.ls(sl=True)
    parentLOC = locList[0]
    childLOC = locList[1]
    sel_sLOC = cmds.xform(parentLOC, q=True, t=True)
    sel_eLOC = cmds.xform(childLOC, q=True, t=True)
    distMaker = cmds.distanceDimension(sp=(sel_sLOC[0], sel_sLOC[1],
                                           sel_sLOC[2]),
                                       ep=(sel_eLOC[0], sel_eLOC[1],
                                           sel_eLOC[2]))
    cmds.rename(distMaker, 'distance1')
    distanceValue = cmds.getAttr('distance1.distance')

    ######## jointNumber ##########
    jn = cmds.intFieldGrp('jointNumber', q=1, value=1)
    jNUM = jn[0]
    ###############################

    #aim Xaxis focus LOC
    aimLocator = cmds.spaceLocator()
    cmds.xform(aimLocator, t=(sel_eLOC[0], sel_eLOC[1], sel_eLOC[2]))
    parentJoint = cmds.joint(p=(sel_sLOC[0], sel_sLOC[1], sel_sLOC[2]))

    cmds.ungroup(aimLocator)
    cmds.aimConstraint(aimLocator, parentJoint, wut=0)
    cmds.delete(aimLocator)

    #parentJoint zeroOut
    y = cmds.xform(parentJoint, q=1, ro=1)
    cmds.joint(parentJoint, e=1, o=(y[0], y[1], y[2]))
    cmds.xform(parentJoint, ro=(0, 0, 0))

    for i in range(1, jNUM + 1):
        iFloating = i * 1.0
        dvPlace = iFloating / jNUM
        transValue = distanceValue * dvPlace
        dpJoint = cmds.duplicate(parentJoint, rr=1)
        #jointOrient
        x = cmds.xform(dpJoint, q=1, ro=1)
        cmds.joint(dpJoint, e=1, o=(y[0], y[1], y[2]))
        cmds.xform(dpJoint, ro=(0, 0, 0))
        cmds.select(dpJoint)
        cmds.move(transValue, 0, 0, r=1, os=1, wd=1)

    cmds.delete('distanceDimension1')
コード例 #28
0
    def mirrorControl(self):
        self.mirrorJointList=[]
        self.mirrorJointList_add=[]
        self.parentGroupList=[]
        sel_re = []
        sel=cmds.ls(sl=True)
        for k in sel:
            tempParentGroupList = cmds.listRelatives( k, allParents=True )
            self.parentGroupList.append(tempParentGroupList)
        for i in sel:
            cmds.select(cl=True)
            cmds.select(i ,r=True)
            tempMirrorJoint = cmds.joint(n='%s_temp_JNT' %i )
            cmds.parent(tempMirrorJoint , w=True)
            cmds.parent(i , tempMirrorJoint)
            self.mirrorJointList.append(tempMirrorJoint)
        #  미러조인트 방법이랑 방향 가져와서 세팅     
        buttonXYZ = self.sender()
        btn = buttonXYZ.objectName()
        btn_XYZ = btn.split('_')

        for i in self.mirrorJointList:
            if self.mirrorCON_world_RDB.isChecked() == True:
                if btn_XYZ[1] == 'X':
                    tempMirrorJoint2 = cmds.mirrorJoint(i , mxy = True , mirrorBehavior=False , searchReplace=('L_', 'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
                elif btn_XYZ[1] == 'Y':
                    tempMirrorJoint2 = cmds.mirrorJoint(i , myz = True , mirrorBehavior=False , searchReplace=('L_', 'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
                elif btn_XYZ[1] == 'Z':
                    tempMirrorJoint2 = cmds.mirrorJoint(i , mxz = True , mirrorBehavior=False , searchReplace=('L_', 'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
            if self.mirrorCON_behavior_RDB.isChecked() == True:
                if btn_XYZ[1] == 'X':
                    tempMirrorJoint2 = cmds.mirrorJoint(i , mxy = True , mirrorBehavior=True , searchReplace=('L_', 'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
                elif btn_XYZ[1] == 'Y':
                    tempMirrorJoint2 = cmds.mirrorJoint(i , myz = True , mirrorBehavior=True , searchReplace=('L_', 'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
                elif btn_XYZ[1] == 'Z':
                    tempMirrorJoint2 = cmds.mirrorJoint(i , mxz = True , mirrorBehavior=True , searchReplace=('L_', 'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
        cmds.ungroup(self.mirrorJointList_add)
        cmds.ungroup(self.mirrorJointList)
コード例 #29
0
    def alignHead(self, playerbody_amount=0, mode=""):
        # Group head mesh + skeleton
        cmds.group(em=True, name='Head')
        cmds.parent("head_mesh" + str(playerbody_amount), "Head")
        cmds.parent("head_skeleton" + str(playerbody_amount), "Head")
        rotation = False

        if mode == "MW 1/2/3":
            head_joint_chain = "|j_spine4"
            body_joint_chain = "|tag_origin|j_mainroot|pelvis|torso_stabilizer|j_spinelower|back_low|j_spineupper|back_mid|j_spine4"
        elif mode == "BO 3/4":
            head_joint_chain = "|tag_origin|j_mainroot|j_spinelower|j_spineupper|j_spine4"
            body_joint_chain = "|j_mainroot|j_spinelower|j_spineupper|j_spine4"
            head_rotation = 90, 0, 80
            rotation = True
        # Allign head with body

        self.movePivot(
            "head_skeleton" + str(playerbody_amount) + head_joint_chain,
            "Head")
        cmds.parentConstraint(
            "body_skeleton" + str(playerbody_amount) + body_joint_chain,
            "Head")
        if rotation:
            cmds.rotate(head_rotation[0],
                        head_rotation[1],
                        head_rotation[2],
                        "Head",
                        absolute=True)
        cmds.delete("Head_parentConstraint1")

        # Attach Head to Torso
        try:
            cmds.delete("body_skeleton" + str(playerbody_amount) +
                        body_joint_chain + "|j_neck")
        except:
            print "Body skeleton had no neck."
        cmds.parent(
            "head_skeleton" + str(playerbody_amount) + head_joint_chain +
            "|j_neck",
            "body_skeleton" + str(playerbody_amount) + body_joint_chain)
        cmds.delete("Head|head_skeleton" + str(playerbody_amount))
        cmds.ungroup("Head")
コード例 #30
0
def removeShadow():
    try:
        cmds.polySeparate(cmds.ls(g=1)[0], ch=0)
    except:
        pass

    for shape in cmds.ls(g=True):
        bbox = cmds.exactWorldBoundingBox(shape)
        if abs(bbox[4] - bbox[1]) <= 1:
            cmds.delete(cmds.listRelatives(shape, p=1)[0])
        else:
            for i in cmds.ls(assemblies=True):
                g = cmds.listRelatives(i, type='transform')
                if g:
                    cmds.select(i)
                    cmds.ungroup()
                    try:
                        cmds.sets(g, e=True, fe='initialShadingGroup')
                    except:
                        pass
    def CenterLocator(self):
        loc = [0, 0, 0]
        sel = mc.ls(sl=True)
        big = len(sel)

        if (big > 0):
            dup = mc.group(sel)

            box = mc.xform(dup, q=True, bb=True)

            loc[0] = ((box[0] + box[3]) / 2)
            loc[1] = ((box[1] + box[4]) / 2)
            loc[2] = ((box[2] + box[5]) / 2)
            mc.warning("! ! ! Locator Successfully Placed ! ! !")

            mc.spaceLocator(p=(loc[0], loc[1], loc[2]), name="Center_Locator")
            mc.ungroup(dup)

        if (big == 0):
            mc.warning(" ! ! ! Must make a selection ! ! !")
コード例 #32
0
ファイル: Blueprint.py プロジェクト: jwnwilson/nw_rig
def mirrorBlueprint( moduleName, args):
    """
        Will mirror blueprint default is in -x axis
    """
    """# get all module transforms
    transforms = ModuleUtil.getRegisteredObjects(moduleName,"regBlueprintTransform")
    # mirror in x default
    for transform in transforms:
        tmpGrp = cmds.group(transform)
        cmds.xform(tmpGrp, ws=True, piv= (0, 0, 0))
        cmds.scale( -1,1,1, tmpGrp)
        #cmds.ungroup( tmpGrp )"""
    # get root mirror it
    rootGrp = (moduleName + "Root_GRP")
    if cmds.objExists(rootGrp):
    	tmpGrp = cmds.group(rootGrp)
        cmds.xform(tmpGrp, ws=True, piv= (0, 0, 0))
        cmds.scale( -1,1,1, tmpGrp)
        cmds.ungroup( tmpGrp )
    else:
        cmds.error("Root group not found when mirroring blueprint")
コード例 #33
0
def create_text(text, font):
    print(font)
    if font == '':
        cmds.textCurves(ch=0, t=text, font=default_font)
    else:
        cmds.textCurves(ch=0, t=text, font=font)
    cmds.ungroup()
    cmds.ungroup()
    curves = cmds.ls(sl=True)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    shapes = curves[1:]
    cmds.select(shapes, r=True)
    cmds.pickWalk(d='Down')
    cmds.select(curves[0], tgl=True)
    cmds.parent(r=True, s=True)
    cmds.pickWalk(d='up')
    cmds.delete(shapes)
    cmds.xform(cp=True)
    cmds.rename(text.lower() + "_crv")
    return cmds.ls(sl=True)[0]
    print(' ')  # Clear Warnings
コード例 #34
0
def cleanProcedure():
    cmds.undoInfo(ock=1)
    sel = cmds.ls(sl=1)
    selRelatives = cmds.listRelatives(sel)
    if selRelatives[0].startswith('instanceAlongCurveLocator'):
        selectedLocator = []
        selectedLocator=cmds.ls(sl=1)
        tempGroupName = ""
        tempGroupName=str(cmds.group(em=1, n='InstanceMesh'))
        selectedMesh = []
        selectedMeshDuplicatedShape = []
        selectedThings = []
        cmds.select(selectedLocator)
        selectedThings=cmds.listRelatives(c=1)
        selectedMesh=cmds.filterExpand(sm=12)
        cmds.select(selectedMesh)
        selectedMeshDuplicatedShape=cmds.listRelatives(c=1)
        eachOverride=selectedMeshDuplicatedShape[0] + ".overrideEnabled"
        cmds.setAttr(eachOverride, 1)
        selectedMeshDuplicated=cmds.duplicate()
        cmds.parent(selectedMeshDuplicated, tempGroupName)
        cmds.ungroup(tempGroupName)
        cmds.delete(selectedLocator)
        cmds.select(selectedMeshDuplicated)
        cmds.polyUnite(centerPivot=1, ch=1, mergeUVSets=1)
        separatedMesh = []
        separatedMesh=cmds.polySeparate(ch=1)
        cmds.CenterPivot()
        separatedMeshGroup=cmds.listRelatives(separatedMesh, p=1)
        cmds.select(separatedMeshGroup)
        cmds.select(selectedMeshDuplicated, add=1)
        cmds.ungroup()
        cmds.DeleteHistory()
        resultAll = cmds.ls(sl=1,o=1)
        result = cmds.filterExpand(resultAll,sm=12)
        toDelete = list(set(resultAll).difference(set(result)))
        cmds.delete(toDelete)

    else:
        try:
            selectedForClean=cmds.ls(sl=1)
            cmds.polyCube(sz=1, sy=1, sx=1, d=1, cuv=4, h=1, ch=1, w=1, ax=(0, 1, 0))
            temp_polyCube=cmds.ls(sl=1)
            cmds.select(selectedForClean)
            cmds.select(temp_polyCube, add=1)
            cmds.CombinePolygons()
            temp_BeforeSeparate=cmds.ls(sl=1)
            cmds.SeparatePolygon()
            temp_AfterSeparate=cmds.ls(sl=1)
            cmds.delete(temp_AfterSeparate[- 1])
            cmds.DeleteHistory()
            temp_father=cmds.listRelatives(temp_AfterSeparate[0], p=1)
            cmds.select(temp_BeforeSeparate)
            cmds.ungroup()
            cmds.delete(selectedForClean)
            cmds.CombinePolygons()
            cmds.DeleteHistory()
        except:
            pass
    cmds.undoInfo(cck=1)
コード例 #35
0
ファイル: testUngroupCmd.py プロジェクト: mattyjams/maya-usd
    def testUngroupSelectionAfterUndoRedo(self):
        ''' '''
        # create a sphere generator
        sphereGen = SphereGenerator(2, self.contextOp, self.proxyShapePathStr)

        # create 2 spheres
        sphere1Path = sphereGen.createSphere()
        sphere2Path = sphereGen.createSphere()

        # create a group
        groupName = cmds.group(ufe.PathString.string(sphere1Path),
                               ufe.PathString.string(sphere2Path))

        # verify selected item is "group1"
        self.assertEqual(len(self.globalSn), 1)
        groupItem = self.globalSn.front()
        if ufe.VersionInfo.getPatchLevel() >= 1:
            self.assertEqual(groupItem.nodeName(), groupName)
        else:
            self.assertEqual(groupItem.nodeName(), "group1")

        # remove group1 from the hierarchy. What should remain
        # is /Sphere1, /Sphere2.
        cmds.ungroup("{},/group1".format(self.proxyShapePathStr))

        # verify that Sphere1 and Sphere2 are selected
        self.assertEqual(len(self.globalSn), 2)
        self.assertEqual(self.globalSn.front().nodeName(), "Sphere1")
        self.assertEqual(self.globalSn.back().nodeName(), "Sphere2")

        # undo again
        cmds.undo()

        # redo again
        cmds.redo()

        # verify that Sphere1 and Sphere2 are selected
        self.assertEqual(len(self.globalSn), 2)
        self.assertEqual(self.globalSn.front().nodeName(), "Sphere1")
        self.assertEqual(self.globalSn.back().nodeName(), "Sphere2")
コード例 #36
0
ファイル: gtcWorkerMaya.py プロジェクト: zhangzhu123/mdkGTC
    def fSceneTidy(self):
        cmds.currentUnit(linear="m")
        geoList = cmds.ls(g=True)
        grp = cmds.group(geoList, absolute=1)
        scenePosition = cmds.xform(grp, q=1, ws=1, rp=1)
        scenePosition = [
            -1 * scenePosition[0], -1 * scenePosition[1], scenePosition[2]
        ]
        #
        bbox = cmds.exactWorldBoundingBox(geoList)
        constH = 23
        xValue = bbox[3] - bbox[0]
        yValue = bbox[4] - bbox[1]
        zValue = bbox[5] - bbox[2]
        tValue = 0
        if xValue > tValue: tValue = xValue
        if yValue > tValue: tValue = yValue
        if zValue > tValue: tValue = zValue
        sceneScale = constH / tValue
        cmds.ungroup(grp)

        return (scenePosition, sceneScale)
コード例 #37
0
 def _decapitate(targets, edges, orig_mesh, index_target=1):
     """ Takes a lsit of target meshes and deparates them from their bodies so we have isolated head meshes
     Args:
         targets [str]: list of target meshes to separate
         edges [str]: list of edges
         orig_mesh (str): the original mesh we are replacing from the blends file name
         index_target (int): used just in case the separate is targetting the wrong index of shell
     Returns [str]: list of face template meshes created from the targets
     """
     blend_table = {}
     
     for edge in [edge for edge in edges if '.' in edge]:
         transform = edge.split('.')[0]
         try:
             blend_table[transform].append(edge)
         except KeyError:
             blend_table[transform] = [edge]
     heads = []
     
     for target in targets:
         for transform, edges in blend_table.iteritems():
             target_shape = mc.listRelatives(target, s=True)[0]
             edges = [edge.replace(transform, target) for edge in edges]
             if mc.ls(edges) and len(list(set(mc.ls(edges))))==len(edges):
                 mc.selectMode(co=True)
                 mc.selectType(alc=0, pe=1)
                 mc.select(mc.ls(edges), r=True)
                 mc.polySplitEdge(operation=1, ch=1)
                 
                 shells = mc.polySeparate(target_shape, ch=False)
                 for index, shell in enumerate(shells):
                     if index != index_target:
                         mc.delete(shell)
                     else:
                         shell=shell
                 mc.ungroup(target, w=True)
                 heads.append(shell)
     mc.selectMode(o=True)
     return heads
コード例 #38
0
def nmGrouper_ungroup():
    '''
	This function will attempt to ungroup the selected items.
	'''
    # sel
    sel = cmds.ls(sl=True)
    if (len(sel) > 0):
        # ungroup selected
        for stuff in sel:
            if (cmds.listRelatives(stuff, c=True)):
                cmds.ungroup(stuff)
                # line
                nmGUI_func.nmGUI_runCheck(
                    'complete', 'Selected objects have been ungrouped.')
            else:
                # line
                nmGUI_func.nmGUI_runCheck(
                    'error', 'Please select a parent node to ungroup.')
    else:
        # line
        nmGUI_func.nmGUI_runCheck('error',
                                  'Please select one or more objects.')
コード例 #39
0
def movePivots():

    pivPos = cmds.radioButtonGrp('pivPos', q=True, sl=True)

    sel = cmds.ls(sl=True)

    # Testing for number of selected objects
    if (len(sel) < 1):
        cmds.error('No objects selected')
    elif (len(sel) == 1):
        if (pivPos == 1):
            cmds.xform(cp=True)  # Centering Pivot
        else:
            bBox = cmds.xform(q=True, ws=True,
                              bb=True)  # Querying bound box info
            centerPos = cmds.xform(q=True, ws=True,
                                   sp=True)  #Querying transform info
            cmds.xform(
                piv=(centerPos[0], bBox[1], centerPos[2]),
                ws=True,
            )  # Adjusting pivot
    else:
        cmds.group(sel, n='pivotTempGrp', w=True)  # Creating temporary group
        objCenter = cmds.objectCenter('pivotTempGrp')
        objBB = cmds.xform('pivotTempGrp', q=True, ws=True,
                           bb=True)  # Querying bound box info for group
        yAverage = ((objBB[1] + objBB[4]) / 2)  # Calculating height
        for i in range(len(sel)):
            cmds.select(sel[i])
            if (pivPos == 1):
                cmds.xform(piv=(objCenter[0], objBB[1], objCenter[2]), ws=True)
            else:
                cmds.xform(piv=(objCenter[0], yAverage, objCenter[2]), ws=True)

        # Deleting temporary group
        cmds.ungroup('pivotTempGrp')

    cmds.select(sel)
コード例 #40
0
    def alignHands(self, playerbody_amount):
        # Group hands mesh + skeleton
        cmds.group(em=True, name='Arms')
        cmds.parent("arms_mesh" + str(playerbody_amount), "Arms")
        cmds.parent("arms_skeleton" + str(playerbody_amount), "Arms")

        # Allign hands with body
        self.movePivot(
            "arms_skeleton" + str(playerbody_amount) +
            "|tag_origin|j_mainroot|j_spinelower|j_spineupper|j_spine4|j_clavicle_le|j_shoulder_le",
            "Arms")
        cmds.parentConstraint(
            "body_skeleton" + str(playerbody_amount) +
            "|j_mainroot|j_spinelower|j_spineupper|j_spine4|j_clavicle_le|j_shoulder_le",
            "Arms")
        cmds.rotate(90, 0, 90, "Arms", absolute=True)
        cmds.delete("Arms_parentConstraint1")

        # Attach Hands to Torso
        cmds.delete(
            "body_skeleton" + str(playerbody_amount) +
            "|j_mainroot|j_spinelower|j_spineupper|j_spine4|j_clavicle_le")
        cmds.delete(
            "body_skeleton" + str(playerbody_amount) +
            "|j_mainroot|j_spinelower|j_spineupper|j_spine4|j_clavicle_ri")
        cmds.parent(
            "arms_skeleton" + str(playerbody_amount) +
            "|tag_origin|j_mainroot|j_spinelower|j_spineupper|j_spine4|j_clavicle_le",
            "body_skeleton" + str(playerbody_amount) +
            "|j_mainroot|j_spinelower|j_spineupper|j_spine4")
        cmds.parent(
            "arms_skeleton" + str(playerbody_amount) +
            "|tag_origin|j_mainroot|j_spinelower|j_spineupper|j_spine4|j_clavicle_ri",
            "body_skeleton" + str(playerbody_amount) +
            "|j_mainroot|j_spinelower|j_spineupper|j_spine4")
        cmds.delete("Arms|arms_skeleton" + str(playerbody_amount))
        cmds.ungroup("Arms")
コード例 #41
0
How to run:
import import_curve
reload (import_curve)


"""
import maya.cmds as cmds
import maya.mel as mel

cmds.file('Autodesk/maya/2011-x64/prefs/icons/icon.ai',
	i=True, type='Adobe(R) Illustrator(R)', ra=True, ns='icon', gr=True,
	gn='icon_pad', pr=True, lrd='all')
print 'Illustrator Path has been imported'

cmds.select('icon_pad')
cmds.ungroup()
cmds.ungroup()
curves = cmds.ls(sl=True)
shapes = cmds.pickWalk(d='down')
print 'Curves have been selected and ungrouped'


cmds.select(shapes[1], curves[0])
cmds.parent(r=True, s=True)
print 'Curves have been combined to a single object'

final = curves[0]
curves.pop(0)
cmds.delete(curves)
cmds.select(final)
mel.eval('CenterPivot')
コード例 #42
0
	def __init__(self):

		selected_objects = cmds.ls(sl=True, transforms=True)

		filtered_groups = []

		for obj in selected_objects:

			if obj.find("Group__") == 0:

				filtered_groups.append(obj)

		if len(filtered_groups) == 0:

			return

		group_container = "Group_container"
		modules = []

		for group in filtered_groups:

			modules.extend(self.find_child_modules(group))

		module_containers = [group_container]

		for module in modules:

			module_container = module+":module_container"
			module_containers.append(module_container)

		for container in module_containers:

			cmds.lockNode(container, lock=False, lockUnpublished=False)

		for group in filtered_groups:

			num_children = len(cmds.listRelatives(group, children=True))

			if num_children > 1:

				cmds.ungroup(group, absolute=True)

			for attr in ["t", "r", "globalScale"]:

				cmds.container(group_container, edit=True, unbindAndUnpublish=group+"."+attr)

			parent_group = cmds.listRelatives(group, parent=True)

			cmds.delete(group)

			if parent_group != None:

				parent_group = parent_group[0]
				children = cmds.listRelatives(parent_group, children=True)
				children = cmds.ls(children, transforms=True)

				if len(children) == 0:

					cmds.select(parent_group, replace=True)
					UngroupSelected()

		for container in module_containers:

			if cmds.objExists(container):

				cmds.lockNode(container, lock=True, lockUnpublished=True)
コード例 #43
0
def connectCarToCraftRig():
	selection = cmds.ls ( selection=True )
	if len ( selection ) == 2:
		if cmds.objExists ( selection[0]+'.isCar' ):
			if selection[1][-20:] == 'CarBodyMeshTransform':
				craftRigName = selection[1][:-20]
				cmds.group ( craftRigName+'TargetMeshTransform' , craftRigName+'GravityDirectionMeshTransform' ,craftRigName+'CarBodyMeshTransform' ,  name=craftRigName+'group')
				cmds.xform ( os=True , piv=( 0, 0, 0 ))
				cmds.setAttr ( craftRigName+'group.rotateY' , 180 )
				cmds.ungroup ( craftRigName+'group' )
			
				carName = selection[0]
				underCarriageY = cmds.getAttr (carName+'_exterior.boundingBoxMinY')
				carLength = cmds.getAttr (carName+'.boundingBoxSizeZ')
				rigLength = 352.0 #baked value - can't get bounding box information becaus of follow cam
			
				cmds.select ( craftRigName+'CarBodyMeshTransform' , replace=True )
				scaleValue = carLength/rigLength
				cmds.scale ( scaleValue, scaleValue, scaleValue, relative=True )
			
				rigFront = cmds.getAttr ( craftRigName+'CarBodyMeshTransform.boundingBoxMaxZ' )
				carFront = cmds.getAttr ( carName+'.boundingBoxMaxZ' )
				cmds.move ( 0 , 0 , carFront-rigFront , relative = True )

				cmds.parentConstraint ( craftRigName+'CarBodyMeshTransform' , carName+'_body' , maintainOffset=True , weight= 1 )
				
				carWheels			= [ carName+'_wheelFL' , carName+'_wheelFR' , carName+'_wheelBL' , carName+'_wheelBR' ]		 
				carBrakes			= [ carName+'_brakeFL' , carName+'_brakeFR' , carName+'_brakeBL' , carName+'_brakeBR' ]
				rigWheels			= [ craftRigName+'WheelMesh_FLTransform' , craftRigName+'WheelMesh_FRTransform' , craftRigName+'WheelMesh_BLTransform' , craftRigName+'WheelMesh_BRTransform' ]
				rigWheelRelocators	= [ craftRigName+'WheelRelocatorMesh_FLTransform' , craftRigName+'WheelRelocatorMesh_FRTransform' , craftRigName+'WheelRelocatorMesh_BLTransform' , craftRigName+'WheelRelocatorMesh_BRTransform' ]
				rigWheelCenters		= [ craftRigName+'WheelCenterMesh_FLTransform' , craftRigName+'WheelCenterMesh_FRTransform' , craftRigName+'WheelCenterMesh_BLTransform' , craftRigName+'WheelCenterMesh_BRTransform' ]

				#Eats some poo - I mean detect namespaces because the wheel nulls are a special name naming convention for AE
				carContactLocators = []
				if ':' in carName:
					print carName+' has namespacing'
					carSplit = carName.split (':')
					namespaceNme = carSplit [0]
					carNameWithoutNamespace = carSplit [1]
					carContactLocators	= [ namespaceNme+':null_'+carNameWithoutNamespace+'_contactFL' , namespaceNme+':null_'+carNameWithoutNamespace+'_contactFR' , namespaceNme+':null_'+carNameWithoutNamespace+'_contactBL' , namespaceNme+':null_'+carNameWithoutNamespace+'_contactBR' ]
				else:
					carContactLocators	= [ 'null_'+carName+'_contactFL' , 'null_'+carName+'_contactFR' , 'null_'+carName+'_contactBL' , 'null_'+carName+'_contactBR' ]


				for i in range (0,4):
					cmds.xform ( carWheels[i] , centerPivots=True)	
					pos = cmds.xform ( carWheels[i] , query=True, rotatePivot=True , worldSpace=True )
					cmds.move ( pos[0],pos[1],pos[2], rigWheelRelocators[i] , worldSpace=True , absolute=True)
					cmds.move ( pos[0],cmds.getAttr ( carWheels[i]+'.boundingBoxMinY' ),pos[2], carContactLocators[i] , worldSpace=True , absolute=True)
	
					rigWheelDiametre = cmds.getAttr ( rigWheels[i]+'.boundingBoxSizeY' )
					carWheelDiametre = cmds.getAttr ( carWheels[i]+'.boundingBoxSizeY' ) 
	
					cmds.select ( rigWheelRelocators[i], replace=True )
					scaleValue = ( carWheelDiametre/rigWheelDiametre ) / cmds.getAttr (craftRigName+'CarBodyMeshTransform.scaleY') / cmds.getAttr ( rigWheelRelocators[i]+'.scaleY')
					cmds.scale ( scaleValue, scaleValue, scaleValue, relative=True )
	
					cmds.select ( rigWheels[i] , replace=True )
					cmds.select ( carWheels[i] , add=True )
	
					cmds.parentConstraint ( rigWheels[i] , carWheels[i] , maintainOffset=True , weight=1 )
					cmds.parentConstraint ( rigWheelCenters[i] , carBrakes[i] , maintainOffset=True , weight=1 )
					
				print 'Car Rigged. Success!'
			else:
				print 'Usage: Select valid car first then command click Craft rig.'
		else:
			print 'Usage: Select valid car first then command click Craft rig.'
	else:
		print 'Usage: Select valid car first then command click Craft rig.'
コード例 #44
0
	def ikSplineSetup(self,*args):
		"""
		 Build IK Spline 
		"""
		#Store ikChain
		mc.select(self.baseJnt,hi=True,r=True)
		ikChain = mc.ls(sl=True,fl=True)
		
		
		# Create hip and shldr jnts
		mc.select(clear=True)
		self.hipJnt = mc.joint( n = self.prefix + 'hipJnt' ) 
		mc.select(clear=True)
		self.shldrJnt = mc.joint( n = self.prefix + 'shldrJnt' ) 
        
		# Snap created joints to base + end joints
		temp = mc.pointConstraint( self.baseJnt, self.hipJnt, mo=False )
		mc.delete( temp )
		temp = mc.pointConstraint( self.endJnt, self.shldrJnt, mo=False )
		mc.delete( temp )
		
		#Match orientations by parenting the jnts, then orienting with none value, then unparenting
		mc.parent(self.hipJnt, self.baseJnt)
		mc.parent(self.shldrJnt, self.endJnt)
		mc.joint(self.hipJnt,e=True, oj='none',zso=True,ch=True)
		mc.joint(self.shldrJnt,e=True, oj='none',zso=True,ch=True)
		mc.parent( self.hipJnt, w=True )
		mc.parent( self.shldrJnt, w=True )
		
		#Set rotation orders based on rotate order of body control
		mc.setAttr(self.hipJnt + ".rotateOrder", (self.rotateOrder))
		mc.setAttr(self.shldrJnt + ".rotateOrder", (self.rotateOrder))
		
		#Value used in spline ik command
		self.numSpans = self.numSpans + 1
		
		#SplineIK for back: Create and store name
		backIkHandle = self.prefix + "back_"
		temp = mc.ikHandle(sj=self.baseJnt,ee=self.endJnt,sol="ikSplineSolver",pcv=False,ns=self.numSpans) 
		backIkHandle = backIkHandle + temp[0]
		mc.rename(temp[0],backIkHandle)
		
		#Get back ik curve name
		temp = mc.listConnections(backIkHandle,s=True)
		for each in temp:
			if "curve" in each:
				backCurve = each #Storing the back ik curve name
		#Name back curve
		temp = self.prefix + '_backIkCrv'		
		mc.rename(backCurve, temp)
		backCurve=temp
				
		#Skin hip/shldr jnt's to back curve
		mc.skinCluster(self.hipJnt,self.shldrJnt,backCurve,dr=4)
		
		#Parent hipsJnt/shldrJnt to controllers
		mc.parent(self.hipJnt,self.hipsCnt)
		mc.parent(self.shldrJnt,self.shldrCnt)
		
		#Turn off inherit transforms on backCurve
		mc.setAttr(backCurve +".inheritsTransform", 0)
		
		#
		#---Set up stretchy
		#
		
		#0Select and store the joints to link in the back expression
		mc.select(self.baseJnt,hi=True,r=True)
		backJoints = mc.ls(sl=1,fl=1,type='joint')
			
		jntNum = len(backJoints)
		

		stretch = '.scale' + self.stretchyAxis  #i.e. 'scaleX'

		#Now,Create curveInfo node 
		curveInfo = mc.arclen(backCurve,ch=1)
		#Rename curve info node
		temp = self.prefix + 'backCrvInfo'
		mc.rename(curveInfo, temp)
		curveInfo = temp
		
		#Create backScaleMD and connect arclength to input1X
		backScaleMD = mc.createNode('multiplyDivide',n=self.prefix + 'backMD')		
		mc.connectAttr(curveInfo + ".arcLength",backScaleMD + ".i1x")	

		#Get ArcLength value, set backScaleMD node to divide by it
		arcLen = mc.getAttr(curveInfo+".arcLength")
		mc.setAttr(backScaleMD+".i2x",arcLen)
		mc.setAttr(backScaleMD+".operation",2) #Divide

		#
		#---Advance Twist setup
		# Make these values variables in the interface...
		mc.setAttr( backIkHandle + ".dTwistControlEnable", 1)	#Enable advanced twist
		mc.setAttr( backIkHandle + ".dWorldUpType", self.worldUpType-1) 	
		mc.setAttr( backIkHandle + ".dWorldUpAxis", self.upAxis-1) 			
		mc.setAttr( backIkHandle + ".dWorldUpVectorX", self.upVecX)		     
		mc.setAttr( backIkHandle + ".dWorldUpVectorY", self.upVecY)		    
		mc.setAttr( backIkHandle + ".dWorldUpVectorZ", self.upVecZ)		    
		mc.setAttr( backIkHandle + ".dWorldUpVectorEndX", self.upVec2X)	    
		mc.setAttr( backIkHandle + ".dWorldUpVectorEndY", self.upVec2Y) 	
		mc.setAttr( backIkHandle + ".dWorldUpVectorEndZ", self.upVec2Z) 	
		
		mc.connectAttr(self.hipsCnt + '.worldMatrix', backIkHandle+'.dWorldUpMatrix', f=True)
		mc.connectAttr(self.shldrCnt + '.worldMatrix', backIkHandle+'.dWorldUpMatrixEnd', f=True)
				
		#
		#---Make volume preservation expression
		#
		
		#Create attributes for each joint so the user can set the 
		# scaling factor per joint via the hipControl
		mc.addAttr(self.hipsCnt,ln='BackVolumeScaleFactor',k=True,dv=0)
		mc.setAttr(self.hipsCnt + '.BackVolumeScaleFactor',lock=True)
		
		x = 0
		for each in backJoints:
				#Not the backBaseJnt
				if(each == self.baseJnt):
					x = x + 1
					continue
				#Skipping the last one
				if( x == (jntNum-1) ):
					x = x + 1
					break
				mc.addAttr(self.hipsCnt,ln=each,dv=1,k=True)
				x = x + 1
		
		backExpString = '//Back volume preservation expression\n'\
		                  '$scale = %s.ox/%s.scaleY;\n'\
		                  '$invScale = 1 / sqrt($scale);\n'\
				          '//Apply scale values to back.\n' % (backScaleMD,self.scaleCnt)
		
					    		   
		#Enter lines in expression string per joint 
		#connecting their scales to the inverse scale with the pow scale factor
		x = 0
		if self.stretchyAxis == 'X':
			for jnt in backJoints:
				#Not the backBaseJnt
				if(jnt == self.baseJnt):
					x = x + 1
					continue
				#Skipping the last one
				if( x == (jntNum-1) ):
					x = x + 1
					break
				temp = '%s.scaleX = $scale;\n' % (jnt) 
				backExpString =  backExpString + temp 
				temp = '%s.scaleY = pow($invScale,%s.%s);\n' % (jnt, self.hipsCnt, jnt) 
				backExpString =  backExpString + temp 
				temp = '%s.scaleZ = pow($invScale,%s.%s);\n' % (jnt, self.hipsCnt, jnt)  
				backExpString =  backExpString + temp
				x = x + 1
				
		if self.stretchyAxis == 'Y':
			for jnt in backJoints:
				#Not the backBaseJnt
				if(jnt == self.baseJnt):
					x = x + 1
					continue
				#Skipping the last one
				if( x == (jntNum-1) ):
					x = x + 1
					break
				temp = '%s.scaleX = pow($invScale,%s.%s);\n' % (jnt, self.hipsCnt, jnt) 
				backExpString =  backExpString + temp 
				temp = '%s.scaleZ = pow($invScale,%s.%s);\n' % (jnt, self.hipsCnt, jnt) 
				backExpString =  backExpString + temp
				x = x + 1
				
		if self.stretchyAxis == 'Z':
			for jnt in backJoints:
				#Not the backBaseJnt
				if(jnt == self.baseJnt):
					x = x + 1
					continue
				#Skipping the last one
				if( x == (jntNum-1) ):
					x = x + 1
					break
				temp = '%s.scaleX = pow($invScale,%s.%s);\n' % (jnt, self.hipsCnt, jnt) 
				backExpString =  backExpString + temp 
				temp = '%s.scaleY = pow($invScale,%s.%s);\n' % (jnt, self.hipsCnt, jnt) 
				backExpString =  backExpString + temp
				x = x + 1
				
		mc.expression( s=backExpString,n=self.prefix+'backVolumeExp' )
		
		#Connect scaleY to X + Z for a global scale effect.
		mc.connectAttr(self.scaleCnt + '.scaleY',self.scaleCnt+'.scaleX',f=True)
		mc.connectAttr(self.scaleCnt + '.scaleY',self.scaleCnt+'.scaleZ',f=True)
			
		#
		#--- Moveable pivot
		#--- Work in progress: Moving on for now, revisit should necessity arrive.			
		"""
		#Create pivot control locator ad snap to body/COG
		pivLoc = mc.spaceLocator()
		temp = mc.parentConstraint(self.hipsCnt,pivLoc,mo=False)
		mc.delete(temp)
		
		#Rename locator
		temp = self.prefix + 'hipsPivot_Ctrl'
		mc.rename(pivLoc,temp)
		pivLoc=temp

		#Attach locator to hipCnt pivot
		mc.connectAttr(pivLoc + '.translate', self.hipsCnt + '.rotatePivot',f=True)	

		#Parent the locator to hipsCnt
		mc.parent(pivLoc,self.hipsCnt)
		#Freeze transform now, so it inherits the orientation of it's parent
		mc.makeIdentity(pivLoc, apply=True )
		"""
		
		#Create the user space locator, the one they interface with.
		#Need to integrate the update pivot functionality to this script.
		# Methods might be a script node/script job that happens when a set attribute changes state, or something...
		#-------< Not finished
		
		#
		#--- FK setup
		#
		if self.fkOnOff == 1: #On
			#build fkChain On ikchain joints
			mc.select(clear=True)
			#Get rotate order from hips control
			rotateOrder = mc.getAttr(self.hipsCnt+'.rotateOrder')
			fkJnts = []
			x = 0
			while x < (self.numFkJnts[0] + 1):
				pos = mc.xform(ikChain[x], query=True,ws=True,t=True)
				#point = mc.xform(fkCrv + '.cv['+str(x)+']', query=True,ws=True,t=True)
				if x == 0: #If first joint
					fkJnts.append( mc.joint( p = (pos) ,n=self.prefix+'fbBackBase' )  )
					#Set rotate order	
					mc.setAttr(fkJnts[x] + '.rotateOrder', rotateOrder)
					x = x + 1
					continue
				if x == ( self.numFkJnts[0] ): #If last joint
					fkJnts.append( mc.joint( p = (pos) ,n=self.prefix+'fkBackEnd' )  )
					break
				else:
					fkJnts.append( mc.joint( p = (pos) ,n=self.prefix+'fkBack_'+str(x) )  )
				#Set rotate order	
				mc.setAttr(fkJnts[x] + '.rotateOrder', rotateOrder)
				
				x = x + 1
			#mc.delete(fkCrv)
			
			""" May not be needed: when building along ik, it will orient to the next joint
				automatically.
			"""
			x = 0	
			for jnt in fkJnts:
				#Parent to baseJnt, makeIdentity to match orientation
				mc.parent( jnt, self.baseJnt )
				mc.makeIdentity(jnt, apply=True, jo=True )
				temp = mc.group( jnt )
				mc.ungroup( temp, w=True )
				#It will always fail with an index out of range error for the fist one.
				try:
					#This puts it back into the fk hierarchy
					mc.parent( jnt, fkJnts[x-1] )
				except:
					pass
				
				x = x + 1
			
			#Create fk controller curves
			x = 0
			for jnt in fkJnts:
				    				
				#Skip the last one
				if x == (len(fkJnts)+1): 
					break
				
				if self.stretchyAxis == 'X':
					tempCnt = mc.circle( nr = (1,0,0),r=self.radius[0] )
				if self.stretchyAxis == 'Y':
					tempCnt = mc.circle( nr = (0,1,0),r=self.radius[0] )
				if self.stretchyAxis == 'Z':
					tempCnt = mc.circle( nr = (0,0,1),r=self.radius[0] )
				
				#Select the shape
				tempShp = mc.pickWalk(tempCnt,direction='down')
				mc.parent(tempShp,jnt,r=True,s=True)
				
				#Delete empty transform
				mc.delete(tempCnt)
				
				x = x + 1
				
			#Parent fkBase joint to body/COG
			mc.parent(fkJnts[0],self.bodyCnt)
			
			#Parent hipCnt to body/COG
			mc.select(self.hipsCnt,r=True)
			bufferGrp = mc.pickWalk(direction='up')
			#bufferGrp = mc.ls(sl=True,fl=True) 
			mc.parent(bufferGrp[0], self.bodyCnt)
			
			#Parent shldrCnt to fkJnts[last one]
			mc.select(self.shldrCnt,r=True)
			bufferGrp = mc.pickWalk(direction='up')
			#bufferGrp = mc.ls(sl=True,fl=True) 
			mc.parent(bufferGrp[0], fkJnts[-1:])
			
			#Grp ikCurve, ikHandle into doNotTouch group
			if mc.objExists(self.prefix + '_NoTouchy'):
				mc.parent(backCurve, backIkHandle, self.prefix + '_NoTouchy')
			else:
				noTouchGrp = mc.group( backCurve, backIkHandle, n = self.prefix + '_NoTouchy') 
            
			#Group + parent joints to world control (ScaleCnt)
			jntsGrp = mc.group( self.baseJnt , n=self.prefix+'_backJntsGrp')
			mc.parent( jntsGrp, self.scaleCnt )
            
			#Get body/COG control buffer, parent it to scaleCnt 
			mc.select(self.bodyCnt,r=True)
			mc.pickWalk(direction='up')
			buffer = mc.ls(sl=True,fl=True)
			mc.parent(buffer,self.scaleCnt)
コード例 #45
0
ファイル: GeoMirrorX.py プロジェクト: lmp3d/lmp3d-maya-py
# GeoMirrorX.py
# Leif Peterson 2016
#
# LMP3D Python Scripts version 1.0
#
# The Following Maya Python Script is intended to be used to mirror an object across the X Axis

import maya.cmds as cmds
import string

# Get Selected Objects
SelectedObjects = cmds.ls( selection=True )

for Object in SelectedObjects:
    NewObject = string.replace( Object, 'Left', 'Right' )
    cmds.duplicate( Object, name=NewObject, upstreamNodes=True )
    Result = cmds.group( NewObject )
    cmds.xform( Result, pivots=[0,0,0] )
    cmds.scale( -1, x=True)
    cmds.ungroup( Result )