Example #1
0
 def createCurve(self):
     self.curve = cmds.curve(p=self.getCurveParam())
     cmds.displaySmoothness(divisionsU=3,
                            divisionsV=3,
                            pointsWire=16,
                            pointsShaded=4,
                            polygonObject=3)
Example #2
0
def load(file_path, obj_name, parent_name):
    """Import a file exported from ZBrush.

    This is the command sent over the Maya command port from ZBrush.

    Parameters
    ----------
    file_path : str
        Path to the file that we are importing
    obj_name : str
        Name of the object being imported
    parent_name : str
        Name of the parent for the object being imported
    """
    file_name = utils.split_file_name(file_path)
    _cleanup(file_name)
    cmds.file(file_path, i=True,
              usingNamespaces=False,
              removeDuplicateNetworks=True)

    # Set smoothing options if necessary
    if cmds.optionVar(ex='gozbruh_smooth') and not cmds.optionVar(q='gozbruh_smooth'):
        cmds.displaySmoothness(obj_name, du=0, dv=0, pw=4, ps=1, po=1)

    if not cmds.attributeQuery("gozbruhParent", n=obj_name, ex=True):
        cmds.addAttr(obj_name, longName='gozbruhParent', dataType='string')
    cmds.setAttr(obj_name + '.gozbruhParent', parent_name, type='string')
Example #3
0
def setBG(*arg):
    '''
	Smooth and render layer set up for selected BGs
	'''

    cmds.displaySmoothness(polygonObject=3)

    selBGs = cmds.ls(sl=True)

    cmds.editRenderLayerGlobals(currentRenderLayer='ch_master')
    for sel in selBGs:
        cmds.editRenderLayerMembers('ch_master', sel, noRecurse=True)
    allShps = cmds.listRelatives(allDescendents=True,
                                 type='mesh',
                                 fullPath=True)
    for shp in allShps:
        cmds.setAttr('%s.primaryVisibility' % shp, 0)

    cmds.editRenderLayerGlobals(currentRenderLayer='bg_master')
    for sel in selBGs:
        cmds.editRenderLayerMembers('bg_master', sel, noRecurse=True)

    cmds.editRenderLayerGlobals(currentRenderLayer='ch_shadows')
    for sel in selBGs:
        cmds.editRenderLayerMembers('ch_shadows', sel, noRecurse=True)
    allShps = cmds.listRelatives(allDescendents=True,
                                 type='mesh',
                                 fullPath=True)
    for shp in allShps:
        cmds.setAttr('%s.castsShadows' % shp, 0)

    cmds.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer')
Example #4
0
def setChar(*arg):
    '''
	Smooth and render layer set up for selected characters
	'''

    cmds.displaySmoothness(polygonObject=3)

    allTrnsf = cmds.listRelatives(allDescendents=True, type='transform')
    if allTrnsf:
        for trnsf in allTrnsf:
            if 'facial' in trnsf:
                cmds.setAttr('%s.visibility' % trnsf, 0)

    selChs = cmds.ls(sl=True)

    for sel in selChs:
        cmds.editRenderLayerMembers('ch_master', sel, noRecurse=True)

    cmds.editRenderLayerGlobals(currentRenderLayer='ch_shadows')
    for sel in selChs:
        cmds.editRenderLayerMembers('ch_shadows', sel, noRecurse=True)
    allShps = cmds.listRelatives(allDescendents=True,
                                 type='mesh',
                                 fullPath=True)
    for shp in allShps:
        cmds.setAttr('%s.primaryVisibility' % shp, 0)

    cmds.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer')
Example #5
0
 def createStalk(self):
     ''' This method creates the stalk. '''
     
     # y ax is calculated by flower position
     mc.polyPipe( subdivisionsHeight=3 );
     mc.scale( 0.24, self.flowerTY+1, 0.24 )
     mc.move( 0, -self.flowerTY/2, 0 );
     mc.displaySmoothness( divisionsU=3, divisionsV=3, pointsWire=16, pointsShaded=4, polygonObject=3 );
     self.currentStalk = mc.ls( sl=True );
     currentStalk0 = self.currentStalk[0]
      
     # bend the stalk
     bendStalkRandomUpX = 1.5 * (1.0 - random.random())
     bendStalkRandomUpZ = 1.5 * (1.0 - random.random())
     for uCV in range (40,60):    
         mc.select( currentStalk0 + ".vtx[" + str(uCV) + "]" );
         mc.move( bendStalkRandomUpX, 0, bendStalkRandomUpZ, r=True );
         mc.select( currentStalk0 + ".vtx[" + str(uCV+60) + "]" );
         mc.move( bendStalkRandomUpX, 0, bendStalkRandomUpZ, r=True );
     
     bendStalkRandomDownX = 1.2 * (1.0 - random.random())
     bendStalkRandomDownZ = 1.2 * (1.0 - random.random())
     for uCV in range (20,40):
         mc.select( currentStalk0 + ".vtx[" + str(uCV) + "]" );
         mc.move( bendStalkRandomDownX, 0, bendStalkRandomDownZ, r=True );
         mc.select( currentStalk0 + ".vtx[" + str(uCV+100) + "]" );
         mc.move( bendStalkRandomDownX, 0, bendStalkRandomDownZ, r=True )
     
     # delete history
     mc.select( currentStalk0 )
     maya.mel.eval( "DeleteHistory" )
     
     mc.select( clear=True )
     
     return self.currentStalk
def setRiggedSmoothPreviews():
	for each in cmds.ls(type = 'mesh'):
		getTransform = cmds.listRelatives(each, parent = True)[0]
		if cmds.objExists('%s.smoothed' % getTransform):
			if cmds.getAttr('%s.smoothed' % getTransform):
				cmds.displaySmoothness(getTransform, polygonObject = 3)
				setSmoothLevelPreviewOne(getTransform)
Example #7
0
    def createBladeOfGrass(self):
        """ This method creates a blade of grass. """

        # random the high of blade
        self.grassHeight = 0.2 * random.randrange(6, 10)

        # create the plane of blade
        mc.polyPlane(axis=(0, 0, 0),
                     subdivisionsX=2,
                     subdivisionsY=6,
                     height=4)
        mc.move(0, 2, 0)
        self.currentBlade = mc.ls(sl=True)

        # create the form of blade
        mc.displaySmoothness(divisionsU=3,
                             divisionsV=3,
                             pointsWire=16,
                             pointsShaded=4,
                             polygonObject=3)
        mc.select(self.currentBlade[0] + ".vtx[18:20]", r=True)
        mc.softSelect(softSelectEnabled=True, ssd=20, sud=0.5)
        mc.scale(0.1, 1, 1, p=(0, 9.86, 0), r=True)
        mc.softSelect(ssd=8.08, sud=0.5)

        # bend the grass
        bendGrassRandom = 15 * (3.0 - random.random())
        mc.rotate(bendGrassRandom, 0, 0, os=True, r=True, p=(0, 9.18, 0))
        mc.select(self.currentBlade)
        extrudeFace = mc.polyExtrudeFacet(self.currentBlade[0] + ".f[0:11]",
                                          constructionHistory=1,
                                          keepFacesTogether=1,
                                          pvx=0,
                                          pvy=4.84,
                                          pvz=0.14,
                                          divisions=1,
                                          twist=0,
                                          taper=1,
                                          off=0,
                                          thickness=0,
                                          smoothingAngle=30)
        mc.setAttr(extrudeFace[0] + ".localTranslate",
                   0,
                   0,
                   0.05,
                   type='double3')
        mc.softSelect(softSelectEnabled=False)

        # scale the blade
        mc.select(self.currentBlade)
        mc.scale(1, self.grassHeight, 1, r=True)

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

        # change the position
        self.changePositionBlade()

        return self.currentBlade
Example #8
0
def toggle(hierarchy=False):
    meshes = get_mesh_objects(Hierarchy if hierarchy else Selected)
    for mesh in meshes:
        try:
            state = cmds.displaySmoothness(str(mesh), q=True, po=True).pop()
        except AttributeError:
            pass
        cmds.displaySmoothness(str(mesh), po=0 if state == 3 else 3)
Example #9
0
 def run(self):
     meshes = mc.ls(type="mesh", long=1)
     if not meshes:
         self.warning_check("No meshes.")
         return
     for mesh in meshes:
         mc.displaySmoothness(mesh, polygonObject=1)
     self.pass_check(u"所有模型处于按1的状态")
 def smoothBtnClick(self):
     btn = self.sender()
     objs = btn.getObjs()
     if btn.state:
         cmds.displaySmoothness(objs, divisionsU=3, divisionsV=3, pointsWire=16, pointsShaded=4, polygonObject=3)
         btn.state = False
     else:
         cmds.displaySmoothness(objs, divisionsU=0, divisionsV=0, pointsWire=4,  pointsShaded=1, polygonObject=1)
         btn.state = True
Example #11
0
def smoothAll(*arg):
    for smoothSet in filter(lambda x: ':' not in x, smoothSetList()) or []:
        value = int(smoothSet[len(smoothSetBodyName):])
        for obj in filterSelection(mc.sets(smoothSet, q=True), 'set'):  # or []
            mc.displaySmoothness(obj, polygonObject=3)
            for shape in mc.listRelatives(obj, s=True, f=True):
                mc.setAttr(shape + '.smoothLevel', value)
                if mc.menuItem(smstUI_optSmRnd_mI, q=True, cb=True):
                    mc.setAttr(shape + '.renderSmoothLevel', value)
Example #12
0
def postSmooth():
    smoothNodes = mc.ls(type='polySmoothFace')
    if smoothNodes:
        for smoothNode in smoothNodes:
            if smoothNode[:12] == 'smoothNode':
                mesh = mc.listConnections(smoothNode + '.output')
                mc.polySmooth(mesh, e=1, dv=0)
                mc.delete(smoothNode)
                mc.displaySmoothness(mesh, polygonObject=3)
        mc.select(clear=True)
Example #13
0
def preSmooth():
    meshes = mc.ls(type='mesh')
    if meshes:
        for mesh in meshes:
            smoothState = mc.displaySmoothness(mesh, q=1, polygonObject=1)
            if smoothState:
                if smoothState[0] == 3:
                    mc.displaySmoothness(mesh, polygonObject=1)
                    #smoothNode = mc.polySmooth(mesh, ch=1, dv=3)
                    #mc.rename(smoothNode,'smoothNode_'+mesh)
                    mc.setAttr('%s.aiSubdivType' % mesh, 1)
                    mc.setAttr('%s.aiSubdivIterations' % mesh, 2)
Example #14
0
def pstCatClark():
    # This Chnages Subdivision States Back To Normal Equals To 1 Smooth In Maya
    smoothShapes = cmds.ls(type='polySmoothFace')

    if smoothShapes:
        for prim in smoothShapes:
            if prim[:10] == 'pRCatClark':
                shapes = cmds.listConnections(prim + '.output')
                cmds.polySmooth(prim, e=True, dv=0)
                cmds.delete(prim)
                cmds.displaySmoothness(shapes, polygonObject=3)
                cmds.select(clear=True)
Example #15
0
def bakeSkins(objects, *args):
    # for each object (transform), create a duplicate, unlock channels, move to world space, freeze xforms, then wrap deform it to the original.
    # disable all display smoothing to speed things up and prevent max from interpreting the points incorrectly.
    print '\nRUNNING bakeSkins'
    polys = cmds.ls(type='mesh')
    cmds.displaySmoothness(polys, du=0, dv=0, pw=4, ps=1, po=1)
    start = cmds.playbackOptions(q=1, min=1)
    end = cmds.playbackOptions(q=1, max=1)
    # create a quick select set to house the deforming geometry. all duplicates will be added to this set for the fbx plugin.
    cmds.select(cl=1)
    exportSet = cmds.sets(text='gCharacterSet', n='FBXExportSet')
    cacheDir = os.path.join(cmds.workspace(q=1, fn=1), 'data', 'FBX',
                            os.path.splitext(cmds.file(q=1, sn=1, shn=1))[0],
                            'pointCache').replace('\\', '/')
    if not os.path.exists(cacheDir): os.makedirs(cacheDir)
    # block the viewport
    mel.eval('setNamedPanelLayout "Single Perspective View"')
    perspPane = cmds.getPanel(vis=1)
    cmds.scriptedPanel('graphEditor1', e=1, rp=perspPane[0])
    # wraps = []
    # cycle through objects
    for obj in objects:
        dupe = cmds.duplicate(obj, rc=1, rr=1)[0]
        chans = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v']
        for i in chans:
            cmds.setAttr(dupe + '.' + i, lock=False)
        try:
            dupe = cmds.parent(dupe, w=1)[0]
        except RuntimeError:
            pass
        cmds.delete(dupe, ch=1)
        blend = cmds.blendShape(obj, dupe, foc=1, origin='world')
        cmds.blendShape(blend, e=1, w=[0, 1.0])
        cmds.sets(dupe, add=exportSet)
        dupeShape = cmds.listRelatives(dupe, s=1, ni=1)[0]
    # next run the MEL export commands for FBX.
    # the FBX plugin will automatically create the geocache, so there's no reason for me to write them out manually.
    mel.eval('FBXResetExport;')
    mel.eval('FBXExportCacheFile -v true;')
    evalStr = 'FBXExportQuickSelectSetAsCache -v ' + exportSet + ';'
    mel.eval(evalStr)
    mel.eval('FBXExportInputConnections -v false;')
    # select the objects to export from the selection set.
    cmds.select(exportSet)
    cmds.select(exportSet, add=1, ne=1)
    fbxFile = os.path.join(
        cacheDir,
        os.path.splitext(cmds.file(q=1, sn=1, shn=1))[0] +
        '_SKINS.fbx').replace('\\', '/')
    evalStr = 'FBXExport -f "' + fbxFile + '" -s'
    mel.eval(evalStr)
    print('Exported skins and point caches to %s') % (fbxFile)
Example #16
0
def preCatClark():
    # This Subdivides Every Polygon Objetcs In Scene Equals To 3 Smooth In Maya
    objects = cmds.ls(type='mesh')

    if objects:
        for shapes in objects:
            smoothState = cmds.displaySmoothness(shapes,
                                                 q=True,
                                                 polygonObject=True)
            if smoothState:
                if smoothState[0] == 3:
                    cmds.displaySmoothness(shapes, polygonObject=1)
                    smoothShapes = cmds.polySmooth(shapes, ch=True, dv=2)
                    cmds.rename(smoothShapes, 'pRCatClark_' + shapes)
Example #17
0
 def smooth(opt):	
     for each in mc.ls(sl=1):
             if opt==1:
                 mc.displaySmoothness(each,divisionsU=0,divisionsV=0, pointsWire=4,pointsShaded=1,polygonObject=1)
                 mc.sets(each,edit=1,fe='smoothSet')
                 mc.setAttr(each+'.useSmoothPreviewForRender',1 )
                 mc.setAttr(each+'.smoothLevel',2)
                 mc.setAttr(each+'.renderSmoothLevel',int(mc.textFieldGrp('rsmoothField',q=1,text=1)) )
             else:
                 mc.displaySmoothness(each,divisionsU=3,divisionsV=3, pointsWire=16,pointsShaded=4,polygonObject=3)
                 #mc.sets(each,edit=1,fe='smoothSet')
                 mc.setAttr(each+'.useSmoothPreviewForRender',0 )
                 mc.setAttr(each+'.smoothLevel',int(mc.textFieldGrp('dsmoothField',q=1,text=1)) )
                 mc.setAttr(each+'.renderSmoothLevel',int(mc.textFieldGrp('rsmoothField',q=1,text=1)) )
Example #18
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]
Example #19
0
def start():
    sel = mc.ls(type='mesh')
    for o in sel:
        mc.displaySmoothness(o,
                             divisionsU=0,
                             divisionsV=0,
                             pointsWire=4,
                             pointsShaded=1,
                             polygonObject=1)
        mc.setAttr(o + '.displaySubdComps', 0)
        mc.setAttr(o + '.smoothLevel', 1)
        try:
            mc.setAttr(o + '.aiSubdivIterations', 2)
            print 'copado'
        except:
            pass
Example #20
0
def findObjectSmoothness():
    allMeshs = []
    allSmoothness = []

    allSelObj = mc.ls(sl=True, dag=True, shapes=True)
    if not allSelObj:
        mc.confirmDialog(message=u"请选择物体!")
        return
    for obj in allSelObj:
        if mc.objectType(obj) == "mesh":
            allMeshs.append(obj)

    if allMeshs:
        for meshs in allMeshs:
            displaySms = mc.displaySmoothness(meshs,
                                              q=True,
                                              polygonObject=True)
            if displaySms:
                if displaySms[0] == 3:
                    allSmoothness.append(meshs)

    if allSmoothness:
        res = mc.confirmDialog(
            message=u"下列是所选物体按3的%s\n是否需要Smoothness\n 是 = Yes,否 = No\n" %
            allSmoothness,
            button=['Yes', 'No'],
            defaultButton='Yes',
            cancelButton='No',
            dismissString='No')
        if res == 'Yes':
            for sm in allSmoothness:
                mc.polySmooth(sm, suv=1, dv=2, ps=0.1, ro=1)
        else:
            return
Example #21
0
def addToSmoothSet(*arg):
    selection = filterSelection(mc.ls(sl=True, l=True), 'scene')
    #value = mc.intSliderGrp(smstUI_smoothLvl_intSG, q=True, value=True)
    value = getSmoothLvl()
    if selection:

        # --- set
        remFromAll()
        createSmoothSet(value)
        inSet = mc.sets(smoothSetName(value), q=True) or []
        mc.sets(selection, add=smoothSetName(value))
        result = list(
            set([sel.rpartition('|')[-1] for sel in selection]) - set(inSet))
        print '# %s added to %s' % (result, smoothSetName(value))
        """
        # --- partition
        createPartition()
        addToPartition(smoothSetName(value))
        """
        # --- options
        options = optWhichNeedLoop()
        if options['loopInObj']:
            for obj in result:
                if mc.menuItem(smstUI_optSmView_mI, q=True, cb=True):
                    mc.displaySmoothness(obj, polygonObject=3)
                if options['loopInShape']:
                    for shape in mc.listRelatives(obj, s=True, f=True):
                        if mc.menuItem(smstUI_optSmPw_mI, q=True, cb=True):
                            mc.setAttr(shape + '.smoothLevel', value)
                        if mc.menuItem(smstUI_optSmRnd_mI, q=True, cb=True):
                            mc.setAttr(shape + '.renderSmoothLevel', value)

        # --- layer
        if mc.menuItem(smstUI_optDispLay_mI, q=True, cb=True):
            createDisplayer(value)
            mc.editDisplayLayerMembers(dispLayerName(value),
                                       result,
                                       noRecurse=True)

    else:
        mc.error(
            'Wrong node type in selection ! Please select geometry transforms only'
        )
Example #22
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]
Example #23
0
def getSmooth(obj=None, fix=True):
    """
    This function check input
    and return true if smooth mode is 3 and 2,
    or false if it's 1
    :param obj: 'list'
    :param fix: 'bool'
    :return: 'dict'
    """
    returnDict = {}
    if obj:
        for o in obj:
            if inPoly.checkInputPoly([o]):
                smooth = cmds.displaySmoothness(o, q=True, po=True)
                if smooth:
                    returnDict[o] = smooth
                    if fix:
                        if smooth == [2L] or [3L]:
                            cmds.displaySmoothness(o, po=1)
    return returnDict
def  createTestShapes():
  import maya.cmds as cmds

  if cmds.objExists('domeTestLight'): 
    print('Removing existing Domemaster3D object: domeTestLight')
    cmds.select( 'domeTestLight', replace=True)
    cmds.delete()

  if cmds.objExists('polyTestSphere'): 
    print('Removing existing Domemaster3D object: polyTestSphere')
    cmds.select( 'polyTestSphere', replace=True)
    cmds.delete()

  if cmds.objExists('polyTestCube'): 
    print('Removing existing Domemaster3D object: polyTestCube')
    cmds.select( 'polyTestCube', replace=True)
    cmds.delete()

  test_sphere_name = cmds.polySphere( name='polyTestSphere', radius=24, subdivisionsX=20, subdivisionsY=20, axis=(0, 1, 0),  createUVs=2, constructionHistory=True)
  cmds.setAttr(test_sphere_name[0]+'.translateX', 80)
  cmds.setAttr(test_sphere_name[0]+'.translateY', 75)

  #Smooth the render time polygon sphere shape
  cmds.displaySmoothness( test_sphere_name, divisionsU=3, divisionsV=3, pointsWire=16, pointsShaded=4, polygonObject=3 )

  test_cube_name = cmds.polyCube( name='polyTestCube', width=40, height=40, depth=40, subdivisionsX=1, subdivisionsY=1, subdivisionsZ=1, axis=(0, 1, 0),  createUVs=4, constructionHistory=True)
  cmds.setAttr(test_cube_name[0]+'.translateX', 0)
  cmds.setAttr(test_cube_name[0]+'.translateY', 75)
  cmds.setAttr(test_cube_name[0]+'.translateZ', -80)
  cmds.setAttr(test_cube_name[0]+'.rotateX', 88)
  cmds.setAttr(test_cube_name[0]+'.rotateY', 0)
  cmds.setAttr(test_cube_name[0]+'.rotateZ', 0)

  dome_light_shape_name = cmds.directionalLight()
  dome_light_name = getObjectParentNode( dome_light_shape_name )
  dome_light_name = cmds.rename (dome_light_name, "domeTestLight")

  cmds.setAttr( (dome_light_name+'.translateX'), -32)
  cmds.setAttr( (dome_light_name+'.rotateX'), 38)
  cmds.setAttr( (dome_light_name+'.rotateY'), 47)
  cmds.setAttr( (dome_light_name+'.rotateZ'), -62)
Example #25
0
def _fx_modelPanel_cleanUp(modelPanel = ''):
	if cmds.modelPanel(modelPanel, exists = True):
		cmds.modelEditor(
						 modelPanel,
						 edit = True,
						 allObjects = False,
						 polymeshes = True,
						 manipulators = True,
						 dynamics = True,
						 fluids = True,
						 nParticles = True,
						 nRigids = True,
						 pluginShapes = True,
						 pluginObjects = ['gpuCacheDisplayFilter', True],
						 displayAppearance = 'smoothShaded',
						)

		for x in cmds.ls(type = 'mesh'):
			smoothnessPreview = cmds.displaySmoothness(x, polygonObject = True, q = True)
			if smoothnessPreview == [3]:
				cmds.displaySmoothness(x, polygonObject = 1)
Example #26
0
    def createStalk(self):
        ''' This method creates the stalk. '''

        # y ax is calculated by flower position
        mc.polyPipe(subdivisionsHeight=3)
        mc.scale(0.24, self.flowerTY + 1, 0.24)
        mc.move(0, -self.flowerTY / 2, 0)
        mc.displaySmoothness(divisionsU=3,
                             divisionsV=3,
                             pointsWire=16,
                             pointsShaded=4,
                             polygonObject=3)
        self.currentStalk = mc.ls(sl=True)
        currentStalk0 = self.currentStalk[0]

        # bend the stalk
        bendStalkRandomUpX = 1.5 * (1.0 - random.random())
        bendStalkRandomUpZ = 1.5 * (1.0 - random.random())
        for uCV in range(40, 60):
            mc.select(currentStalk0 + ".vtx[" + str(uCV) + "]")
            mc.move(bendStalkRandomUpX, 0, bendStalkRandomUpZ, r=True)
            mc.select(currentStalk0 + ".vtx[" + str(uCV + 60) + "]")
            mc.move(bendStalkRandomUpX, 0, bendStalkRandomUpZ, r=True)

        bendStalkRandomDownX = 1.2 * (1.0 - random.random())
        bendStalkRandomDownZ = 1.2 * (1.0 - random.random())
        for uCV in range(20, 40):
            mc.select(currentStalk0 + ".vtx[" + str(uCV) + "]")
            mc.move(bendStalkRandomDownX, 0, bendStalkRandomDownZ, r=True)
            mc.select(currentStalk0 + ".vtx[" + str(uCV + 100) + "]")
            mc.move(bendStalkRandomDownX, 0, bendStalkRandomDownZ, r=True)

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

        mc.select(clear=True)

        return self.currentStalk
 def ApplySmooth(self):
     cmds.displaySmoothness(divisionsU = 0, divisionsV = 0, pointsWire = 4, pointsShaded = 1, polygonObject = 1)
     
     for mesh in cmds.listRelatives(cmds.getAttr("CMSettings.ModelName"), allDescendents = True, type = "mesh"):
         #If the mesh is an intermediate object ignore it
         try:
             if cmds.getAttr( mesh + ".intermediateObject"):
                 continue;
         except:
             pass
         
         #Try to delete smooth on the current mesh
         try:
             cmds.setAttr(mesh + "Smooth.divisions", 0)
             cmds.delete(mesh + "Smooth")
         except:pass
         
         #Try to apply smooth on the mesh
         try:
             Smooth = cmds.polySmooth(mesh, dv = 0)
             cmds.rename(Smooth, mesh+"Smooth")
         except:pass
Example #28
0
 def createBladeOfGrass(self):
     """ This method creates a blade of grass. """
     
     # random the high of blade
     self.grassHeight = 0.2 * random.randrange ( 6, 10 );
     
     # create the plane of blade
     mc.polyPlane( axis=(0, 0, 0), subdivisionsX=2, subdivisionsY=6, height=4 );
     mc.move( 0, 2, 0 )
     self.currentBlade = mc.ls( sl=True );
     
     # create the form of blade
     mc.displaySmoothness( divisionsU=3, divisionsV=3, pointsWire=16, pointsShaded=4, polygonObject=3 );
     mc.select( self.currentBlade[0] + ".vtx[18:20]", r=True ) ;
     mc.softSelect( softSelectEnabled=True, ssd=20, sud=0.5 );
     mc.scale( 0.1, 1, 1, p=(0, 9.86, 0), r=True );
     mc.softSelect( ssd=8.08, sud=0.5 );
     
     # bend the grass
     bendGrassRandom = 15 * (3.0 - random.random())
     mc.rotate( bendGrassRandom, 0, 0, os=True, r=True, p=(0, 9.18, 0) );
     mc.select( self.currentBlade )
     extrudeFace = mc.polyExtrudeFacet( self.currentBlade[0] + ".f[0:11]", constructionHistory=1, keepFacesTogether=1, pvx=0, pvy=4.84, pvz=0.14, divisions=1, twist=0, taper=1, off=0, thickness=0, smoothingAngle=30 );
     mc.setAttr( extrudeFace[0] + ".localTranslate", 0, 0, 0.05, type='double3' );
     mc.softSelect( softSelectEnabled=False )
     
     # scale the blade
     mc.select( self.currentBlade )
     mc.scale( 1, self.grassHeight, 1, r=True )
     
     # delete history
     maya.mel.eval( "DeleteHistory" )
     
     # change the position
     self.changePositionBlade()
     
     return self.currentBlade
    def buttoncyclo_onClicked(self):
        # CREATE CURTAIN
        if not cmds.objExists("Cyclo"):
            cmds.polyCube(n="Cyclo", d=20, h=20, w=20)
            cmds.xform("Cyclo", t=[0, 10, 0])
            deletableFaces = cmds.ls("Cyclo.f[0]", "Cyclo.f[1]", "Cyclo.f[4]", "Cyclo.f[5]")
            cmds.delete(deletableFaces)
            cmds.select("Cyclo.e[5:7]")
            cmds.polySplitRing(sma=30, wt=0.4)
            cmds.select("Cyclo.e[3:5]")
            cmds.polySplitRing(sma=30, wt=0.4)
            cmds.displaySmoothness("Cyclo", po=3)
            cmds.delete("Cyclo", ch=True)
            cmds.parent("Cyclo", "Studio")

            # CREATE CURTAIN MATERIAL
            shader = cmds.shadingNode("aiStandard", n="aiStandard#", asShader=True)
            shaderGroup = cmds.sets(renderable=True, n="%sSG" % shader, noSurfaceShader=True, empty=True)
            cmds.connectAttr("%s.outColor" % shader, "%s.surfaceShader" % shaderGroup)
            cmds.setAttr("%s.diffuseRoughness" % shader, 1)
            cmds.select("Cyclo")
            cmds.hyperShade(assign=shader)
        else:
            print "Cyclo already exist"
Example #30
0
def selectDisplaySmoothnessObjects():
    '''{'path':'Polygons/EditMesh/selectDisplaySmoothnessObjects( )',
'icon':':/subdivPolyMode.png',
'html':False,
'usage':"""
#选择当前选择的物体中按3显示的mesh物体
$fun( )""",
}
'''
    allMeshFullPath = cmds.listRelatives(cmds.ls(sl=True),
                                         type='mesh',
                                         noIntermediate=True,
                                         ad=True,
                                         f=True)
    allMeshFullPath = [
        child for child in allMeshFullPath
        if not cmds.getAttr(child + '.intermediateObject')
    ]
    smoothed = [
        obj for obj in allMeshFullPath
        if cmds.displaySmoothness(obj, q=True, polygonObject=True)[0] > 1
    ]
    cmds.select(smoothed, r=True)
Example #31
0
def smoothPreviewToggle():
    # list all objects
    allObjects = cmds.ls(shapes=True)
    allMesh = []
    smoothed = []
    # get meshes
    for obj in allObjects:
        if cmds.nodeType(obj) == 'mesh':
            allMesh.append(obj)
    # get smoothed
    for node in allMesh:
        # check for notes
        list = cmds.attributeQuery('notes', node=node, ex=True)
        # notes dont exist
        if not list:
            cmds.select(node)
            disSm = cmds.displaySmoothness(query=True, polygonObject=1)
            # get smoothed
            if disSm == [3L]:
                print node
                smoothed.append(node)
                cmds.addAttr(node, ln='notes', sn='nts', dt='string')
                cmds.setAttr(node + '.notes', 'smoothed', type='string')
                cmds.select(cl=True)
            else:
                cmds.select(cl=True)
        # notes do exist
        else:
            # get notes
            note = cmds.getAttr(node + '.notes')
            # get smoothed
            if note == 'smoothed':
                smoothed.append(node)
    # toggle smooth mesh preview
    for shapes in smoothed:
        cmds.select(shapes)
        disSm = cmds.displaySmoothness(query=True, polygonObject=1)
        if disSm == [3L]:
            cmds.displaySmoothness(polygonObject=1)
        else:
            cmds.displaySmoothness(polygonObject=3)
def ExecTurntable():
	#==============================================================
	# SHOTGUN GET INFORMATIONS
	#==============================================================
	def getTank():
		if _platform == "win32":
			ProjectPath= "W:\WG\Shotgun_Configs\RTS_Master"
		elif _platform == "linux" or _platform == "linux2":
			ProjectPath="/srv/projects/rts/WG/Shotgun_Configs/RTS_Master"
		else:
			ProjectPath= "W:/WG/Shotgun_Configs/RTS_Master"
		return sgtk.sgtk_from_path(ProjectPath)
	
	tk = getTank()
	sg = tk.shotgun
	
	ScenePath= cmds.file (q=True, sn=True)
	PathWithoutFileName = os.path.split(ScenePath)[0]
	
	tk.reload_templates()

	ContextFromPath = tk.context_from_path(ScenePath)
	
	AssetIdNumber = ContextFromPath.entity.get('id') 

	TemplateFromPath = tk.template_from_path(ScenePath)
	TemplateFields = TemplateFromPath.get_fields(ScenePath)

	AssetType = TemplateFields.get('sg_asset_type')
	AssetName = TemplateFields.get('Asset')
	StepName = TemplateFields.get('Step')
	# format the version with 3 digits
	# VersionScene = '%0*d' % (03, TemplateFields.get('version'))
	VersionScene = TemplateFields.get('version')

	VersionKey = TemplateFromPath.keys['version']
	VersionKeyFormated= VersionKey.str_from_value(VersionScene)

	AssetRenderTemplate = tk.templates['maya_asset_render']
	AssetRenderFullPath = AssetRenderTemplate.apply_fields(TemplateFields)
	AssetRenderPathAndFileBase = AssetRenderFullPath.split('.')[0]
	AssetRenderPath = AssetRenderFullPath.rsplit('\\', 1)[0]
	AssetRenderFile = AssetRenderFullPath.split('\\')[-1]

	#GET PATH OF LAST VERSION OF TURNTABLE SCENE
	fields = ['id', 'code', 'sg_status_list']
	filters = [
		['project','is',{'type':'Project','id':66}],
		['id','is',1022]
		]
	asset= sg.find_one("Asset",filters,fields)
	PublishTemplate = tk.templates['maya_asset_publish']
	listscenerender= []
	PublishsScenesPaths = tk.paths_from_template(PublishTemplate, asset)
	for PublishScene in PublishsScenesPaths:
		if "turntableCharacter" in PublishScene:
			listscenerender.append(PublishScene)
	listscenerender.sort()
	LastTurntablePath = listscenerender[-1]

	#==============================================================
	#RENDER TURNTABLE TD V0.02
	#==============================================================

	CurrentFolder = os.path.dirname(os.path.realpath(__file__))
	# SaveChanges()
	#NUMBER OF GROUPS IN SCENE VERIFICATION
	curentSel = cmds.ls(g=True, an= True, l=True )
	
	list_grps = []
	for theString in curentSel:
		theSplitAr = theString.split(":")
		if theSplitAr [1][:-1] in list_grps:
			None
		else:
			list_grps.append(theSplitAr [1][:-1])
	Grp_AssetName = "GRP_"+AssetName
	if len(list_grps)!= 1:
		cmds.warning("-program need 1 group named: " + Grp_AssetName)
	elif Grp_AssetName not in list_grps :
		cmds.warning("-program need 1 group named: " + Grp_AssetName)
	else:
		print ("1 groupe = OK")
		GroupName = list_grps [0] 

		#PATHS AND TYPE FILE
		#turntableScenePath = 'C:/Users/tdelbergue/Desktop/'
		#turntableScenePath = "W:/RTS/Experimental/People/TDelbergue/"
		turntableScenePath = "W:/RTS/_Library/Presets/Maya/"
		turntableSceneName= 'scene_turntable_07.ma'
		# turntableSceneName= turntableScene

		LibraryPath = "W:/RTS/_Library"
		RendersPath = "W:/RTS/Renders/_Library/mod"
		WorkMayaPath = "work/maya"
		PublishMayaPath = "publish/maya"

		CurrentMayaPath = PathWithoutFileName+"/"

		#OPEN SCENETURNTABLE
		cmds.file(new=True, force=True)
		cmds.file( LastTurntablePath, o=True )
		
		ImportPreviousScene = cmds.file(ScenePath, i=True, pn= True)  	
		cmds.parent( Grp_AssetName, 'locator_fix' )
		
		SceneTurnOutputName = AssetRenderFile.split('.')[0]+'_turn'
		cmds.file(rename =CurrentMayaPath+SceneTurnOutputName)
		cmds.file(save=True)

		#BOUNDING BOX CREATION
		
		locFixSel = cmds.listRelatives("locator_fix", allDescendents=True, noIntermediate=True, s=False, f=True)
		mySel =cmds.select(locFixSel)
		Isel = cmds.ls( selection=True,s=False )

		XMIN=[]
		YMIN=[]
		ZMIN=[]
		XMAX=[]
		YMAX=[]
		ZMAX=[]

		for i in Isel:
			if "Shape" in i:
				None
			else:
				IselBBox = cmds.xform(i, q=True ,bb=True )
				XMIN.append(IselBBox[0])
				YMIN.append(IselBBox[1])
				ZMIN.append(IselBBox[2])
				XMAX.append(IselBBox[3])
				YMAX.append(IselBBox[4])
				ZMAX.append(IselBBox[5])

		Xwidth =(max(XMAX)- min(XMIN))
		Ywidth =(max(YMAX)- min(YMIN))
		Zwidth =(max(ZMAX)- min(ZMIN))
		
		ratioHautMoitie = Ywidth/2

		heightBoundBoxMin= 2.193*Ywidth
		widthBoundBoxMin= 1.425* Xwidth
		
		if heightBoundBoxMin >=  widthBoundBoxMin:
			cmds.setAttr( "camWide.translateZ",heightBoundBoxMin- min(ZMIN))
		if heightBoundBoxMin <=  widthBoundBoxMin:
			cmds.setAttr( "camWide.translateZ",widthBoundBoxMin- min(ZMIN))
		
		cmds.setAttr( "camWide.translateY", ratioHautMoitie )
		
		#SMOOTH MESHES under locator_fix
		# locator_fix_ChildMeshes = cmds.listRelatives( 'locator_fix', ad=True, typ='mesh' )
		# cmds.select( locator_fix_ChildMeshes )
		# cmds.displaySmoothness( du=3, dv=3, pw=16, ps=4,po=3 )
		meshs = cmds.ls(l=True, typ= 'mesh' )
		cmds.select( meshs )
		cmds.displaySmoothness( du=3, dv=3, pw=16, ps=4,po=3 )
		#SCENE PARAMETERS
		#HD720
		cmds.setAttr ("defaultResolution.width", 1280)
		cmds.setAttr ("defaultResolution.height", 720)
		cmds.setAttr ("defaultResolution.deviceAspectRatio",1.777)
		cmds.setAttr ("defaultResolution.pixelAspect", 1)

		#OUTPUT FRAMES NAME
		cmds.setAttr("defaultRenderGlobals.imageFilePrefix", AssetRenderFile.split('.')[0],type="string")
			
		# EYES MESH IN SCENE VERIFICATION
		eyeList = []
			
		allObjects = cmds.ls(l=False, typ= 'mesh' )

		for obj in allObjects:
			if "eye" in obj.lower():
				EyesTrsX = cmds.objectCenter(obj,x=True)
				EyesTrsY = cmds.objectCenter(obj,y=True)
				EyesTrsZ = cmds.objectCenter(obj,z=True)
				eyeList.append(obj)
		
		#WARNING MESSAGES IF MISSING EYES OR GROUP PROBLEMS
		if not eyeList and AssetType == "Prop" or AssetType == "Vehicle" :
			print "prop with no eyes"
			cameraObj = "camMiddle"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",0)
			cameraObj = "camCloseUp"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",0)
			cameraObj = "camWide"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",1)
			# save wide
			cmds.file(rename = CurrentMayaPath+SceneTurnOutputName+'Wide')
			cmds.file(save=True)
			
		if not eyeList and AssetType == "Character":
			cmds.warning("no object with name 'eye' was found, please rename or create one")	
			
		sumX = []
		sumY = []
		sumZ = []
		#print eyeList
		if eyeList:
			for obj in eyeList:
				EyesTrsX = cmds.objectCenter(obj,x=True)
				EyesTrsY = cmds.objectCenter(obj,y=True)
				EyesTrsZ = cmds.objectCenter(obj,z=True)
				sumX.append(EyesTrsX)
				sumY.append(EyesTrsY)
				sumZ.append(EyesTrsZ)    

			EyesTrsX = sum(sumX)/len(sumX)
			EyesTrsY = sum(sumY)/len(sumY)
			EyesTrsZ = sum(sumZ)/len(sumZ)

			cmds.spaceLocator(p=(EyesTrsX,EyesTrsY,EyesTrsZ), name="pivot_head")
			cmds.parent( "pivot_head", eyeList[0][:-5] )
				
			heightToptoEyes = (max(YMAX)-EyesTrsY) 

			cmds.setAttr( "pivot_camCloseUp.translateX", EyesTrsX )
			cmds.setAttr( "pivot_camCloseUp.translateY", EyesTrsY )
			cmds.setAttr( "pivot_camCloseUp.translateZ", EyesTrsZ ) 

			cmds.parent( "pivot_camCloseUp", "pivot_head" )

			#cmds.setAttr( "camCloseUp.translateY", EyesTrsY )
			cmds.setAttr( "camCloseUp.translateZ", 7*heightToptoEyes- min(ZMIN) )
			#eyes one third from the top:
			# cmds.setAttr( "camCloseUp.translateY", EyesTrsY+ ((heightToptoEyes/3)*2))
			Zwide =getAttr( "camWide.translateZ" )
			Zcloseup =getAttr( "camCloseUp.translateZ" )
			CAM3Z = Zwide - ((Zwide-Zcloseup)/2)

			# cmds.setAttr( "camMiddle.translateZ", 2*Ywidth )
			cmds.setAttr( "camMiddle.translateZ", CAM3Z)

			cmds.setAttr("camMiddle.translateY",(ratioHautMoitie+EyesTrsY)/2)
			
			#CHECK IF CAM ORDER (FAR > NEAR IS OKAY, INVERT IF NOT )
			if Zwide < Zcloseup:
				cmds.setAttr("camWide.translateZ",Zcloseup)
				cmds.setAttr("camCloseUp.translateZ",Zwide)
			
			#IF OTHER RENDER LAYERS DELETE THEM:
			for each in cmds.ls(type='renderLayer'):
				if each != 'defaultRenderLayer':
					cmds.delete(each) 
					
			#CREATE_SCENES_AND_CAMS
			cmds.file(rename = CurrentMayaPath+SceneTurnOutputName+'CloseUp')
			cmds.file(save=True)

			cameraObj = "camCloseUp"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",0)
			cameraObj = "camWide"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",1)
			#save wide
			cmds.file(rename = CurrentMayaPath+SceneTurnOutputName+'Wide')
			cmds.file(save=True)

			cameraObj = "camWide"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",0)
			cameraObj = "camMiddle"
			cmds.lockNode(cameraObj+".renderable", lock=False)
			cmds.setAttr(cameraObj+".renderable",1)
			#save mid
			cmds.file(rename = CurrentMayaPath+SceneTurnOutputName+'Middle')
			cmds.file(save=True)
			#save close
			cmds.file( q=True, ex=True )
		
		#==============================================================
		#DEADLINE SUBMIT
		#==============================================================
		def submitturntable (CharName, CameraName, frameRangeInput ):
			# scenePath = CurrentMayaPath+CharName+"/"
			if not os.path.exists(AssetRenderPath):
				os.makedirs(AssetRenderPath)
			
			Deadline = Connect.DeadlineCon('srv-deadline2', 8080 )
			# Deadline = Connect.DeadlineCon('192.168.0.77', 8080 )

			JobInfo = {
				"Name" : CharName + "_v_"+VersionKeyFormated+ " -" + "turntable" + "- " + CameraName,
				"UserName" : UserName,
				"Frames" : frameRangeInput,
				"Pool" : "maya",
				"Plugin" : "MayaCmd",
				"MachineName": ComputerName,
				# LimitGroups=maya
				"LimitGroups":"maya"

				}
				
			PluginInfo = {
				"Version":"2013",
				"Build":"None",
				"StrictErrorChecking":"True",
				"LocalRendering":"False",
				"MaxProcessors":"0",
				"CommandLineOptions":"",
				"UseOnlyCommandLineOptions":"0",
				"IgnoreError211":"False",
				"SceneFile":PathWithoutFileName+"/"+SceneTurnOutputName+CameraName+".ma",
				"OutputFilePath":AssetRenderPath+"/",
				"Renderer":"MentalRay",
				"Priority":"50"
				}
				
			newJob = Deadline.Jobs.SubmitJob(JobInfo, PluginInfo,idOnly=False)
			print newJob["_id"]
			return newJob["_id"]
			
		# -------------------------------------------------------------------------------------------------
		# ADDING ONE JOB AS A DEPENDENCY
		# -------------------------------------------------------------------------------------------------
		
		def submitTurnChildJob (JobsDepId):
			Deadline = Connect.DeadlineCon('srv-deadline2', 8080 )
			# Deadline = Connect.DeadlineCon('192.168.0.77', 8080 )
			JobInfo = {
				"Name" : AssetName+" Child Job - Make complete sequence ",
				"UserName" : UserName,
				"Frames" : 0,
				"Pool" : "small_tasks",
				"Plugin" : "Python",
				"MachineName": ComputerName,
				"JobDependencies": JobsDepId
			}

			PluginInfo = {
				"Version":2.7,
				"ScriptFile": os.path.abspath(CurrentFolder+"/FillMissingFiles03.py"),
				"Arguments":
				'entityTypeArg='+str(AssetType)+' '+
				'pathArg='+str(AssetRenderPath+"/")+' '+
				'nameArg='+str(AssetRenderFile.split('.')[0])+' '+
				'VersionArg='+str(VersionKeyFormated)+' '+
				'IDAssetArg='+str(AssetIdNumber)
			}

			newJob = Deadline.Jobs.SubmitJob(JobInfo, PluginInfo,idOnly=False)
			print newJob["_id"]	
			
		# -------------------------------------------------------------------------------------------------	

		if AssetType == "Character":			
			JobID1 = submitturntable (AssetName,"Wide", "0-159" )
			JobID2 = submitturntable (AssetName,"Middle", "160-319x10" )
			JobID3 = submitturntable (AssetName,"CloseUp", "320-479x20" )
			JobsDepId = "%s,%s,%s" %(JobID1, JobID2, JobID3)
			childJob = submitTurnChildJob(JobsDepId)
			
		if AssetType == "Prop" or AssetType == "Vehicle" :
			JobID1 = submitturntable (AssetName,"Wide", "0-159" )
			JobsDepId = "%s" %(JobID1)
			childJob = submitTurnChildJob(JobsDepId)
Example #33
0
def cleanAssetScene(fType, *args):
    """cleans up the stuff in the scene (deletes unwanted stuff, etc)"""
    #generically to geo and rig files
    #remove namespaces
    ns = cFuncs.removeNamespace()
    print "removed namespaces: {0}".format(ns)

    ###### ---------- clash fix should happen BEFORE master. . .
    cfix = 1  #1 = fix the clashes, 0 = just report the clashes
    cClash.clash(cfix)

    # clean up the delete set
    if cmds.objExists("deleteSet"):
        delStuff = cmds.sets("deleteSet", q=True)
        cmds.delete(delStuff)
        try:
            cmds.delete("deleteSet")
        except:
            print "-Problem deleting the deleteSet"

    #import all refs
    refs = cmds.file(q=True, r=True)
    for ref in refs:
        refNode = cmds.referenceQuery(ref, rfn=True)
        cmds.file(rfn=refNode, ir=True)

    #delete image planes
    ip = cmds.ls(type="imagePlane")
    print "deleting image planes: {0}".format(ip)
    if ip:
        cmds.delete(ip)

    #delete camera bookmarks
    bm = cmds.ls(type="cameraView")
    print "deleting camera bookmarks: {0}".format(bm)
    if bm:
        cmds.delete(bm)

    #get all lights and delete
    if assOptions["light"]:
        lights = cFuncs.getLightList()
        print "deleting lights: {0}".format(lights)
        if lights:
            cmds.delete(lights)

    #get extra cameras and delete
    if assOptions["cam"]:
        cams = cFuncs.getCamList()
        print "deleting non-default cameras: {0}".format(cams)
        if cams:
            cmds.delete(cams)

    #delete all TIME BASED anim curves (not setdriven keys)
    anmsT = cmds.ls(type=("animCurveTL", "animCurveTU", "animCurveTA",
                          "animCurveTT"))
    if anmsT:
        print "deleting time-based anim curves: {0}".format(anmsT)
        cmds.delete(anmsT)

    #get rid of display layers, render layers, anm layers
    dl = cmds.ls(type="displayLayer")
    if dl:
        dl.remove("defaultLayer")
        print "deleting display layers: {0}".format(dl)
        cmds.delete(dl)

    rl = cmds.ls(type="renderLayer")
    if rl:
        rl.remove("defaultRenderLayer")
        print "deleting render layers: {0}".format(rl)
        cmds.delete(rl)

    al = cmds.ls(type="animLayer")
    if al:
        al.remove("BaseAnimation")
        print "deleting anim layers: {0}".format(al)
        cmds.delete(al)

    #delete unknown nodes
    uk = cmds.ls(type="unknown")
    if uk:
        print "deleting unknown nodes: {0}".format(uk)
        for node in uk:
            cmds.lockNode(node, l=False)
        cmds.delete(uk)

    #check for shaders
    if assOptions["shd"]:
        clnShd.cleanShaders()

    #grab list of all transforms
    allGeo = cmds.listRelatives(cmds.ls(geometry=True), p=True)
    #remove lattices from list
    for g in allGeo:
        if cmds.listRelatives(g, shapes=True, type="lattice"):
            allGeo.remove(g)

    allTransforms = cmds.ls(type="transform")

    #get rid of face assigments (select only the first shader assigned)
    for geo in allGeo:
        shps = cmds.listRelatives(geo, s=True)
        if shps:
            for shp in shps:
                sg = cmds.listConnections(shp, type="shadingEngine")
                if (sg and len(sg) > 1):
                    cmds.sets(geo, e=True, forceElement=sg[0])
                    print "Found more than one shader on {0}. Reassigning to {1}".format(
                        geo, sg[0])

#if geo file . . .
    if fType == "geo":

        #delete history on all geo objects
        cmds.delete(allGeo, ch=True)

        #delete deformers left over (should be none)
        # for geo in allGeo:
        # 	df = mel.eval("findRelatedDeformer {0}".format(geo))
        # 	if df:
        # 		print "deleting deformers: {0}".format(df)
        # 		cmds.delete(df)

        #parent all transforms to world
        for i in allGeo:
            print "------ {0}".format(i)
            if cmds.listRelatives(i, p=True):
                cmds.parent(i, world=True)

        #delete constraints
        cnstrs = cmds.ls(type="constraint")
        print "deleting constraints: {0}".format(cnstrs)
        if cnstrs:
            cmds.delete(cnstrs)

        #delete all sets
        removeSets = ["defaultLightSet", "defaultObjectSet"]
        setList = cmds.ls(et="objectSet")
        for rmSt in removeSets:
            setList.remove(rmSt)
        if setList:
            cmds.delete(setList)

        #delete all expressions
        exprs = cmds.ls(type="expression")
        print "deleting expressions: {0}".format(exprs)
        if exprs:
            cmds.delete(exprs)

        #delete all UNIT BASED anim curves (sdks, etc)
        sdkAnms = cmds.ls(type=("animCurveUL", "animCurveUU", "animCurveUA",
                                "animCurveUT"))
        if sdkAnms:
            print "deleting unit-based anim curves: {0}".format(sdkAnms)
            cmds.delete(sdkAnms)

        allTransforms = cmds.ls(type="transform")

        #delete groups - because DAG should be flattened we can just delete a transform w/o children
        grps = [
            x for x in allTransforms if not cmds.listRelatives(x, shapes=True)
        ]
        if grps:
            print "deleting empty groups: {0}".format(grps)
            cmds.delete(grps)

        allTransforms = cmds.ls(type="transform")
        #delete connections(should be no more anim, constraints at this point, so these would be direct connections)
        for trans in allTransforms:
            #disconnect all channelbox channels
            cons = cmds.listConnections(trans, plugs=True, s=True)

            if cons:
                for con in cons:
                    dest = cmds.connectionInfo(con, dfs=True)
                    if dest:
                        cmds.disconnectAttr(con, dest[0])

        #freeze transforms on geo
        if allGeo and assOptions["freeze"]:
            print "masterFuncs.cleanAssetScene: assOptions[freeze] = {0}\nallGeo = {1}".format(
                assOptions["freeze"], allGeo)
            cmds.makeIdentity(allGeo, apply=True)
        else:
            print "-- not freezing geo"

        #delete all namespaces
        cFuncs.removeNamespace()

        #check for "geo_" name - warn out of this
        geoName = cmds.ls("geo_*")
        if geoName:
            cmds.warning(
                "the following objects have 'geo_' as their prefix!\n{0}".
                format(geoName))

        #set displaySmoothness to 3
        cmds.displaySmoothness(allGeo, polygonObject=1)

        #set ctrl size node
        if cmds.objExists("*ctrlSizeTemplateCrv"):
            ctrl = cmds.ls("*ctrlSizeTemplateCrv")[0]
            #measure distance (10.421 is scale 1)
            pos6 = cmds.pointPosition("{0}.cv[6]".format(ctrl))
            pos18 = cmds.pointPosition("{0}.cv[18]".format(ctrl))
            dist = pos6[0] - pos18[0]
            factor = dist / 10.421

            rigScale = cmds.shadingNode("multiplyDivide",
                                        asUtility=True,
                                        n="RIGDATA")
            cmds.addAttr(rigScale, ln="scaleCtrl", at="float", dv=1.0)
            cmds.setAttr("{0}.scaleCtrl".format(rigScale), factor)
            cmds.delete(ctrl)

#if rig file . . .
    print "Doing rig cleanup stuff. . . "
    if fType == "rig":
        if cmds.objExists("*RIGDATA"):
            rigDataStuff = cmds.ls("*RIGDATA")
            cmds.delete("*RIGDATA")

        # put all ctrls into ALLKEYABLE
        cFuncs.crvsToAllkeyable()
        print "putting all crvs under god node into allkeyable set"
Example #34
0
def toggle_all(state):
    meshes = get_mesh_objects(All)
    for mesh in meshes:
        cmds.displaySmoothness(str(mesh), po=3 if state else 0)
Example #35
0
 def killSmoothing(self,*args):
     # remove smooth preview from all polygon objects.
     meshes = cmds.ls(type='mesh')
     if meshes:
         cmds.displaySmoothness(meshes,du=0,dv=0,pw=4,ps=1,po=1)
 def CreateArchive(*args):
     cmds.confirmDialog(m = "This action will create a copy of the scene in the temp dir")
         
     ExportTypes = cmds.textScrollList("ExportTextScrollList", query = True, si = True)
     
     for Type in ExportTypes:
         if Type == "ma" or Type == "mb":
             #Save the file copy in the new path
             if Type == "ma":
                 cmds.file( save = True, type='mayaAscii' )
             else:
                 cmds.file( save = True, type='mayaBinary' )
             
             cmds.editRenderLayerGlobals( currentRenderLayer = "defaultRenderLayer")
             
             ShadersFile.ShaderClass.DeleteWireframeShader()
             ShadersFile.ShaderClass.DeleteUVMat()
             if not cmds.objExists("ShadowPlane"):
                 ShadersFile.ShaderClass.DeleteVrayShadowMat()
                 ShadersFile.ShaderClass.DeleteMRShadowMat()
                 
             ModelName = cmds.getAttr("CMSettings.ModelName")
             
             ProjectPath = cmds.getAttr("CMSettings.ProjectPath")
             
             try:cmds.delete("CMSettings")
             except:pass
             
             if cmds.objExists("RWSPlane"):
                 cmds.delete("RWSPlane")
             if cmds.objExists("RWSTexture"):
                 cmds.delete("RWSTexture")
             if cmds.objExists("RWSTexturePlacer"):
                 cmds.delete("RWSTexturePlacer")
             if cmds.objExists("RWSShader"):
                 cmds.delete("RWSShader")
             if cmds.objExists("RWSShaderSG"):
                 cmds.delete("RWSShaderSG")
             
             try:cmds.delete("CMBackground")
             except:pass
             
             SceneParts = ["ShadowPlane", "CMLightRig", "UserLights", "CMBackground"]
             for i in SceneParts:
                 if (not cmds.checkBox( i + "CheckBox", query = True, value = True)) and cmds.objExists(i):
                     if i == "ShadowPlane": 
                         ShadersFile.ShaderClass.DeleteVrayShadowMat()
                         ShadersFile.ShaderClass.DeleteMRShadowMat()
                     if i == "CMLightRig":
                         try: cmds.delete("EnvironmentGamma")
                         except:pass
                     try:cmds.delete(i)
                     except:pass
                 
             #Delete all animations
             try:cmds.cutKey(ModelName)
             except:pass
             
             for mesh in cmds.listRelatives(ModelName, children = True):
                 try:cmds.setAttr(mesh + "Smooth.divisions", 0)
                 except:pass
                 try:cmds.delete(mesh + "Smooth")
                 except:pass
         
             
             #Move the persp to the signatures place
             for i in range(0,len(SnapShotFile.SnapShotClass.SnapShots)):
                 if cmds.getAttr(SnapShotFile.SnapShotClass.SnapShots[i].Camera+'.CMSignature') == True:
                         SnapShotFile.SnapShotClass.SnapShots[i].CopyCameraInfo()
             
             cmds.editRenderLayerGlobals( currentRenderLayer = "defaultRenderLayer")
             
             try:cmds.delete("Signature")
             except:pass
             
             try:cmds.delete("SQRSignature")
             except:pass
             
             try:cmds.delete("ContextSig")
             except:pass
             
             try:cmds.delete("Product")
             except:pass
             
             for i in TurntableFile.TurntableClass.Turntables:
                 try:cmds.delete(i.RenderLayer)
                 except:pass
             
             try:cmds.delete("Wireframe")
             except:pass
             
             try:cmds.delete("Subdivision_0")
             except:pass
             
             try:cmds.delete("Subdivision_1")
             except:pass
             
             try:cmds.delete("UVs")
             except:pass
             
             mel.eval("BakeAllNonDefHistory;")
             #cmds.delete(all = True, constructionHistory = True)
             
             #Delete all cameras
             for i in SnapShotFile.SnapShotClass.SnapShots:
                 cmds.camera(i.Camera, edit = True, startupCamera = False)
             
             for i in TurntableFile.TurntableClass.Turntables:
                     cmds.camera(i.Camera, edit = True, startupCamera = False)
             
             CameraList = SnapShotFile.SnapShotClass.SnapShots
             for i in CameraList:
                 if cmds.getAttr(i.Camera + ".CMSignature"):
                     cmds.setAttr(i.Camera + ".backgroundColor", 0.968627, 0.968627, 0.968627, type = "double3")
                     cmds.rename(i.Camera, ModelName + "Camera")
                     try:cmds.delete(i.Camera + "_ImagePlane")
                     except:pass
                 else:
                     cmds.delete(i.Camera)
             
             CameraList = TurntableFile.TurntableClass.Turntables
             for i in TurntableFile.TurntableClass.Turntables:
                 cmds.delete(i.Camera)
             
             try:cmds.delete("CMForegroundPlane")
             except:pass
             try:cmds.delete("CMBackgroundPlane")
             except:pass
                 
             cmds.select(all = True)
             cmds.editDisplayLayerMembers(ModelName + "_layer", cmds.ls(selection = True), noRecurse = True  )
             cmds.displaySmoothness(divisionsU = 1,divisionsV = 1, pointsWire = 8, pointsShaded = 2, polygonObject = 2)
             for mesh in cmds.ls(sl = True):
                     try: 
                         cmds.setAttr(mesh + ".renderSmoothLevel", 1)
                     except:
                         pass
             
             #Save the file
             if Type == "ma":
                 cmds.file( rename = ProjectPath + "/temp/" + "/CM_" + ModelName + ".ma" )
                 cmds.file( save = True, type='mayaAscii' )
             else:
                 cmds.file( rename = ProjectPath + "/temp/" + "/CM_" + ModelName + ".mb" )
                 cmds.file( save = True, type='mayaBinary' )
             
             #Create the zip file
             if Type == "ma":
                 zipf = zipfile.ZipFile(ProjectPath + "/" + ModelName + '_ma.zip', 'w')
             else:
                 zipf = zipfile.ZipFile(ProjectPath + "/" + ModelName + '_mb.zip', 'w')
                 
             
             #write to the zip file
             if Type == "ma":
                 zipf.write(ProjectPath + "/temp/" + "CM_" + ModelName + ".ma", os.path.basename(ProjectPath + "/temp/" + "CM_" + ModelName + ".ma"))                
             else:
                 zipf.write(ProjectPath + "/temp/" + "CM_" + ModelName + ".mb", os.path.basename(ProjectPath + "/temp/" + "CM_" + ModelName + ".mb"))                
             
                 
             
             ##### Get textures ####
             def GetTextures():
                 Textures = []
                 
                 for i in cmds.ls(textures = True):
                     try:
                         Textures.append(cmds.getAttr(i + ".fileTextureName"))
                     except:
                         pass
                 #Remove duplicates    
                 return list(set(Textures))
             
             for i in GetTextures():
                 try:
                     zipf.write(i, os.path.basename(i))
                 except:
                     print "Could not write file ", i , " to zip"
             zipf.close()
             
         else:            
             #Create the export file
             try:
                 fileName = cmds.file(ProjectPath+ "/Temp/" + "CM_" + ModelName, exportAll = True, type = Type )
             except:
                 print "Failed to export scene in format :" , Type
                 continue
             
             #Create the zip file
             zipf = zipfile.ZipFile(ProjectPath + "/" + ModelName + '_' + Type +'.zip', 'w')
             
             #Iges format returns a wrong path fix it 
             if not os.path.exists(fileName):
                 Name, fileExtension = os.path.splitext(fileName)
                 if fileExtension == ".iges":
                     fileName = Name + ".igs"
             
             #Write the file into the zip
             try:
                 zipf.write(fileName, os.path.basename(fileName))
             except:
                 print "Could not write the format:", Type, " to zip file"
             
             #Write the textures in the zip
             for i in GetTextures():
                 try:
                     zipf.write(i, os.path.basename(i))
                 except:
                     pass
             zipf.close()
     
     cmds.displaySmoothness(divisionsU = 0,divisionsV = 0, pointsWire = 4, pointsShaded = 1, polygonObject = 1)
     
     #Save the file
     fileName = cmds.file(l = True, q = True)
     fileName = fileName[0]
     Extension = os.path.splitext(fileName)[1]
     if Extension == '.ma':            
         cmds.file( save = True, type='mayaAscii' )
     elif Extension == '.mb':
         cmds.file( save = True, type='mayaBinary' )
     elif Extension == "":
         cmds.file( save = True, type='mayaAscii' )
     
     cmds.confirmDialog(m = "The orginal file has been saved in the project folder")
     
     #Check to see if the window exists if it does delete it
     if cmds.dockControl("CMMainDock", exists = True):
         try:
             cmds.deleteUI("CMMainDock")
         except:
             print "Could not delete Main Dock"
     elif cmds.window("CMMainWindow", exists = True):
         try:
             cmds.deleteUI("CMMainWindow")
         except:
             print "Could not delete Main Window"
     
     if cmds.headsUpDisplay('SnapButton', exists = True):
         cmds.headsUpDisplay('SnapButton', rem = True)
     
     cmds.select(cmds.listRelatives(cmds.ls(cameras = True, lights = True),parent = True))
     try:
         cmds.select("UserLights", add = True)
     except:
         pass
     try:
         cmds.select("CMLightRig", add = True)
     except:
         pass
     try:
         cmds.editDisplayLayerMembers( 'CM_Lights_and_Cameras', cmds.ls(selection = True) )
     except:
         pass
Example #37
0
    def createJointMover(self, name=None, pos=(0,0,0), matrix=None, scale=1, toroidRatio=0.02, ss=0, facialNode=None):
        try:
            cmds.undoInfo(openChunk=True)
            if not name:
                name = 'test'
            radius = 1

            #create mask attachment node
            maskAttach = cmds.spaceLocator(name=name+'_mover_maskAttach')[0]

            #create jeremy-joint-mover-stack
            topNode = cmds.group(name=name+'_mover_grp', em=1)
            mover = utils.createCircleControl(name=name+'_mover', radius=2, type='toroid', heightRatio=toroidRatio)
            #offset = utils.createCircleControl(name=name+'_mover_offset', radius=1.5, color='xyz', type='toroid', heightRatio=toroidRatio)
            offset = cmds.group(name=name+'_mover_offset', em=1)
            lra_grp = cmds.group(name=name+'_lra_grp', em=1)
            lra = utils.createLRA(name=name + '_LRA', length=2, thickness=0.05, arrowRadiusMult=3)
            cmds.parent(mover, topNode)
            cmds.parent(offset, mover)
            cmds.parent(lra_grp, offset)
            cmds.parent(lra, lra_grp)
            cmds.displaySmoothness(mover, f=1)
            if scale is not 1:
                cmds.scale(scale, scale, scale, topNode)
                cmds.makeIdentity(topNode, apply=1, t=0, r=0, s=1, n=0, pn=1)
            if not ss:
                cmds.select(topNode)
            cmds.parentConstraint(maskAttach, topNode)

            #create SDK pose stack
            sdkOffset = cmds.group(name=name+'_SDK_grp', em=1)
            sdk = utils.createLRA(name=name + '_SDK', length=2, color=False, thickness=0.05, arrowRadiusMult=3)
            tweak = cmds.group(name=name+'_TWEAK', em=1)
            if scale is not 1:
                cmds.scale(scale, scale, scale, sdk)
                cmds.makeIdentity(sdk, apply=1, t=0, r=0, s=1, n=0, pn=1)
            cmds.parent(tweak, sdk)
            cmds.parent(sdk, sdkOffset)
            cmds.parentConstraint(lra, sdkOffset)
            utils.toggleShapeSelection(sdk, False)

            #cleanup outliner
            if cmds.objExists('maskAttachNodes'):
                cmds.parent(maskAttach, 'maskAttachNodes')
            if cmds.objExists('sdkNodes'):
                cmds.parent(sdkOffset, 'sdkNodes')
            if cmds.objExists('jointMovers'):
                cmds.parent(topNode, 'jointMovers')

            #make internal attrs/connections
            utils.msgConnect(mover + '.lra', lra + '.jointMover')
            utils.msgConnect(mover + '.attachNode', maskAttach + '.jointMover')
            utils.msgConnect(mover + '.sdk', sdk + '.jointMover')

            #make external attrs/connections
            if facialNode:
                locs = None

                #mark attachLocations
                try:
                    locs = self.mask.attachLocations
                    locs.extend(maskAttach)
                    self.mask.attachLocations = locs
                except Exception as e:
                    print(traceback.format_exc())

                #hang the jm off the facial node
                utils.msgConnect(self.node + '.jointMovers', mover + '.facialNode')

                #mark jointMovers
                jm = self.jointMovers
                jm.append(mover)
                self.jointMovers = jm

                #mark sdks
                s = self.sdks
                s.append(sdk)
                self.sdks = s

            #stamp with alignment type
            cmds.addAttr(sdk, ln='alignmentType', enumName='mask surface:manual',  k=1, at='enum')

            cmds.undoInfo(closeChunk=True)
            cmds.select(maskAttach)
            return [topNode, lra, offset, maskAttach]
        except Exception as e:
            cmds.undoInfo(closeChunk=True)
            import sys
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(e, fname, exc_tb.tb_lineno)
def setAllSmoothPreviews(state = 0):
	"""
	Function to turn the state for all the smooth mesh previews
	valid states are 0 1 2  = off, cage+smoothed, smoothed
	"""
	cmds.displaySmoothness(cmds.ls(type = 'mesh'), polygonObject = state)
Example #39
0
def toggleDisplay(currentPanel, mode):
    states = []

    if mode == 'isoSelect': # hotkey (alt + h)
        state = cmds.isolateSelect(currentPanel, q=True, state=True)
        if state:
            cmds.isolateSelect(currentPanel, state = False)
            cmds.isolateSelect(currentPanel, removeSelected=True)
        else:
            cmds.isolateSelect(currentPanel, state = True)
            cmds.isolateSelect(currentPanel, addSelected=True)
            
    if mode == 'showAll': #hotkey (alt + `)
        states.append(cmds.modelEditor(currentPanel, q=True, nurbsCurves=True))
        states.append(cmds.modelEditor(currentPanel, q=True, polymeshes=True))
        states.append(cmds.modelEditor(currentPanel, q=True, joints=True))
        
        if states[0] and states[1] and states[2]:
            cmds.modelEditor (currentPanel, edit=True, allObjects = False)
        else:
            cmds.modelEditor (currentPanel, edit=True, allObjects = True)

    if mode == 'curve': #hotkey (alt + 1)
        state = cmds.modelEditor(currentPanel, q=True, nurbsCurves=True)
        cmds.modelEditor (currentPanel, edit=True, nurbsCurves = not state)
        
    if mode == 'surface': #hotkey (alt + 2)
        state = cmds.modelEditor(currentPanel, q=True, nurbsSurfaces=True)
        cmds.modelEditor (currentPanel, edit=True, nurbsSurfaces = not state)

    if mode == 'mesh': #hotkey (alt + 3)
        state = cmds.modelEditor(currentPanel, q=True, polymeshes=True)
        cmds.modelEditor (currentPanel, edit=True, polymeshes = not state)

    if mode == 'locator': #hotkey (alt + 4)
        state = cmds.modelEditor(currentPanel, q=True, locators=True)
        cmds.modelEditor (currentPanel, edit=True, locators = not state)
                
    if mode == 'joint': #hotkey (alt + 5)
        state = cmds.modelEditor(currentPanel, q=True, joints=True)
        cmds.modelEditor (currentPanel, edit=True, joints = not state)

    if mode == 'deformer': #hotkey (alt + 6)
        state = cmds.modelEditor(currentPanel, q=True, deformers=True)
        cmds.modelEditor (currentPanel, edit=True, deformers = not state)

    if mode == 'wireframe': # hotkey (4)
        states.append(cmds.modelEditor(currentPanel, q=True, displayAppearance=True))
        states.append(cmds.modelEditor(currentPanel, q=True, wireframeOnShaded=True))
        
        if states[0] == "smoothShaded":
            if states[1]: 
                cmds.modelEditor (currentPanel, edit=True, wireframeOnShaded=False)
                cmds.modelEditor (currentPanel, edit=True, displayAppearance='wireframe')
            else:
                cmds.modelEditor (currentPanel, edit=True, wireframeOnShaded=True)
        else:
            cmds.modelEditor (currentPanel, edit=True, displayAppearance='smoothShaded')

    if mode == 'jointXray': # hotkey (5)
        state = cmds.modelEditor(currentPanel, q=True, jointXray=True)
        cmds.modelEditor (currentPanel, edit=True, jointXray = not state)
        
    if mode == 'texture': #hotkey (6)
        state = cmds.modelEditor(currentPanel, q=True, displayTextures=True)
        cmds.modelEditor (currentPanel, edit=True, displayTextures = not state)
        
    if mode == 'light': #hotkey (7)
        state = cmds.modelEditor(currentPanel, q=True, displayLights=True)
        if state == "default":
            cmds.modelEditor (currentPanel, edit=True, displayLights = "all")
        else:
            cmds.modelEditor (currentPanel, edit=True, displayLights = "default")

    if mode == 'smooth': #hotkey (0)
        states = cmds.displaySmoothness(q=True, polygonObject=True)
        if states[0] == 1:
            cmds.displaySmoothness(polygonObject=3)
        else:
            cmds.displaySmoothness(polygonObject=1)
Example #40
0
    def _publish_fx_renders_for_item(self, item, output, work_template, primary_publish_path, sg_task, comment, thumbnail_path, progress_cb):
        """
        Render the FX Splashes (any nParticles) with Hardware Render Buffer (HWB)
        """
        ## Do the regular Shotgun processing now
        group_name = item['name'] # spriteSpray_nParticle_T_RShape
        debug(app = None, method = '_publish_fx_renders_for_item', message =  'group_name: %s' % group_name, verbose = False)

        tank_type = 'Rendered Image' # Alembic Cache
        debug(app = None, method = '_publish_fx_renders_for_item', message =  'tank_type: %s' % tank_type, verbose = False)

        publish_template = output["publish_template"] # <Sgtk TemplatePath maya_shot_fxRenderFinal: episodes/{Sequence}/{Shot}//FxLayers/R{version}>
        debug(app = None, method = '_publish_fx_renders_for_item', message =  'publish_template: %s' % publish_template, verbose = False)

        # Get the current scene path and extract fields from it
        # Using the work template:
        scene_path = os.path.abspath(cmds.file(query=True, sn= True)) # I:\bubblebathbay\episodes\ep106\ep106_sh030\FX\work\maya\ep106sh030.v025.ma
        debug(app = None, method = '_publish_fx_renders_for_item', message =  'scene_path: %s' % scene_path, verbose = False)

        fields = work_template.get_fields(scene_path) # {'Shot': u'ep106_sh030', 'name': u'ep106sh030', 'Sequence': u'ep106', 'Step': u'FX', 'version': 25, 'group_name': u'spriteSpray_nParticle_T_RShape'}

        publish_version = fields["version"]

        ## Update fields with the group_name
        fields["group_name"] = group_name

        ## Get episode and shot name from field directly
        epShotName = fields["name"]

        ## create the publish path by applying the fields
        ## with the publish template:
        publish_path = publish_template.apply_fields(fields) # K:\bubblebathbay\episodes\ep106\ep106_sh030\FxLayers\R025

        ## Make the publish directory for images rendering to be placed
        if not os.path.isdir(publish_path):
            os.mkdir(publish_path)

        # ## Hardware Render Buffer settings (LEGACY FOR NOW)
        # ## Get shotCam
        # shotCam = []
        # for cam in cmds.ls(cameras = 1):
        #     if not cmds.camera(cam, query = 1, startupCamera = 1):
        #         transform = cmds.listRelatives(cam, parent = True, fullPath = True)[0]
        #         if cmds.objExists('%s.type' % transform):
        #             if cmds.getAttr('%s.type' % transform) == 'shotCam':
        #                 shotCam.append(transform)
        #
        # if shotCam:
        #     debug(app = None, method = '_publish_fx_renders_for_item', message =  'shotCam for Hardware Render Buffer: %s' % shotCam[0], verbose = False)
        #
        #     ## Set the necessary correct settings for the HWB
        #     mel.eval('glRenderWin;')
        #     cmds.setAttr('defaultHardwareRenderGlobals.filename', epShotName, type = 'string')
        #     cmds.setAttr('defaultHardwareRenderGlobals.extension', 4)
        #     cmds.setAttr('defaultHardwareRenderGlobals.startFrame', cmds.playbackOptions(q = True, min = True))
        #     cmds.setAttr('defaultHardwareRenderGlobals.endFrame', cmds.playbackOptions(q = True, max = True))
        #     cmds.setAttr('defaultHardwareRenderGlobals.byFrame', 1)
        #     cmds.setAttr('defaultHardwareRenderGlobals.imageFormat', 19) # TARGA
        #     cmds.setAttr('defaultHardwareRenderGlobals.resolution', 'HD_720 1280 720 1.777', type = 'string')
        #     cmds.setAttr('defaultHardwareRenderGlobals.alphaSource', 0)
        #     cmds.setAttr('defaultHardwareRenderGlobals.writeZDepth', 0)
        #     cmds.setAttr('defaultHardwareRenderGlobals.lightingMode', 0)
        #     cmds.setAttr('defaultHardwareRenderGlobals.drawStyle', 3)
        #     cmds.setAttr('defaultHardwareRenderGlobals.texturing', 1)
        #     cmds.setAttr('defaultHardwareRenderGlobals.lineSmoothing', 1)
        #     cmds.setAttr('defaultHardwareRenderGlobals.fullImageResolution', 1)
        #     cmds.setAttr('defaultHardwareRenderGlobals.geometryMask', 1)
        #     cmds.setAttr('defaultHardwareRenderGlobals.backgroundColor', 0, 1, 0, type = 'double3')
        #     cmds.glRenderEditor('hardwareRenderView', edit = True, lookThru = shotCam[0])
        #     cmds.workspace(fileRule = ['images', publish_path])
        #     cmds.glRender(renderSequence = 'hardwareRenderView')

        ###############################################################################################
        ## Playblast Render
        ###############################################################################################
        # Get shotCams
        non_startup_cams = [cmds.listRelatives(cam, parent = True, fullPath = True)[0] for cam in cmds.ls(cameras = True) if not cmds.camera(cam, query = True, startupCamera = True)]
        shotCam = [cam for cam in non_startup_cams if cmds.objExists('%s.type' % cam)]
        shotCamShape = [cmds.listRelatives(cam, shapes = True, fullPath = True)[0] for cam in shotCam if cmds.getAttr('%s.type' % cam) == 'shotCam']

        # Get model panel
        model_panel = cmds.getPanel(withFocus = True)

        proceed = False
        if not shotCamShape:
            cmds.warning('No shotCam found in scene, please fix it first...!')
        else:
            if not cmds.objExists('ocean_dispShader'):
                cmds.warning('ocean_dispShader not found in scene, please fix it first...!')
            else:
                if not cmds.objExists('oceanPreviewPlane_heightF'):
                    cmds.warning('oceanPreviewPlane_heightF not found in scene, please fix it first...!')
                else:
                    if not 'modelPanel' in model_panel:
                        cmds.warning('No valid modelPanel in focus for playblasting...!')
                    else:
                        proceed = True

        if proceed == True:
            for cam in shotCamShape:
                ## Set appropriate camera display option settings for optimal playblasting
                cmds.setAttr('%s.overscan' % cam, 1)
                cmds.setAttr('%s.displayFilmGate' % cam, 0)
                cmds.setAttr('%s.displayResolution' % cam, 0)
                cmds.setAttr('%s.displayGateMask' % cam, 0)
                cmds.setAttr('%s.displayFieldChart' % cam, 0)
                cmds.setAttr('%s.displaySafeAction' % cam, 0)
                cmds.setAttr('%s.displaySafeTitle' % cam, 0)
                cmds.setAttr('%s.displayFilmPivot' % cam, 0)
                cmds.setAttr('%s.displayFilmOrigin' % cam, 0)

            ## Set appropriate "SHOW" to modelPanel
            cmds.modelEditor(model_panel, edit = True, displayLights = 'none')
            cmds.modelEditor(model_panel, edit = True, displayLights = 'default', camera = shotCamShape[0], allObjects = False, polymeshes = True, nParticles = True, manipulators = True, pluginShapes = True, pluginObjects = ['gpuCacheDisplayFilter', True], useDefaultMaterial = True, displayAppearance = 'flatShaded', displayTextures = True)

            ## Set lambert1 to green matte
            cmds.setAttr("lambert1.color", 0, 10, 0, type = 'double3')
            cmds.setAttr("lambert1.transparency", 0, 0, 0, type = 'double3')
            cmds.setAttr("lambert1.ambientColor", 0, 10, 0, type = 'double3')
            cmds.setAttr("lambert1.incandescence", 0, 10, 0, type = 'double3')
            cmds.setAttr("lambert1.diffuse", 0)
            cmds.setAttr("lambert1.translucence", 0)
            cmds.setAttr("lambert1.translucenceDepth", 0)
            cmds.setAttr("lambert1.translucenceFocus", 0)

            ## Set ocean shader to green matte
            if cmds.isConnected('ocean_dispShader.outColor', 'oceanPreviewPlane_heightF.color'):
                cmds.disconnectAttr('ocean_dispShader.outColor', 'oceanPreviewPlane_heightF.color')
                cmds.setAttr('oceanPreviewPlane_heightF.color', 0, 1, 0, type = 'double3')

            ## Set view port BG to green matte
            default_bg_color = cmds.displayRGBColor('background', q = True)
            default_bgTop_color = cmds.displayRGBColor('backgroundTop', q = True)
            default_bgBtm_color = cmds.displayRGBColor('backgroundBottom', q = True)
            cmds.displayRGBColor('background', 0, 1, 0)
            cmds.displayRGBColor('backgroundTop', 0, 1, 0)
            cmds.displayRGBColor('backgroundBottom', 0, 1, 0)

            ## Get timeslider min/max
            min = cmds.playbackOptions(min = True, q = True)
            max = cmds.playbackOptions(max = True, q = True)

            ## Force current time to min of time slider to avoid popping at frame 1 issue
            [cmds.currentTime(min) for i in range(2)]

            ## Now find the fx stuff and make sure the groups are visible and good for playblasting
            grps = ['OCEAN_hrc', 'oceanPreviewPlane_prv']
            for eachGrp in grps:
                if cmds.objExists(eachGrp):
                    cmds.setAttr('%s.visibility' % eachGrp, True)
            cmds.select(clear = True)

            ## Find all mesh in scene that has smoothed checked and Mentalray preview smooth them...
            mesh_with_smoothTag = [cmds.listRelatives(mesh, parent = True, fullPath = True)[0] for mesh in cmds.ls(type = 'mesh') if cmds.objExists('%s.smoothed' % cmds.listRelatives(mesh, parent = True, fullPath = True)[0])]
            mesh_with_smoothTag = [mesh for mesh in mesh_with_smoothTag if cmds.getAttr('%s.smoothed' % mesh)]
            [cmds.displaySmoothness(each, polygonObject = 3) for each in mesh_with_smoothTag if 'CHAR_' in each or 'PROP_' in each]

            ## Playblast rendering
            cmds.playblast( filename = os.path.join(publish_path, epShotName).replace('\\', '/'),
                            clearCache = True,
                            startTime = min,
                            endTime = max,
                            viewer = False,
                            forceOverwrite = True,
                            format = 'image',
                            compression = 'png',
                            framePadding = 4,
                            offScreen = True,
                            options = False,
                            percent = 100,
                            quality = 100,
                            sequenceTime = False,
                            showOrnaments = False,
                            widthHeight = [(1280 * 3), (720 * 3)]
                            )

            ## Find all mesh in scene and un-preview smooth them...
            [cmds.displaySmoothness(mesh, polygonObject = 1) for mesh in cmds.ls(type = 'mesh')]

            ## After playblast, set back the scene BG's color as default
            cmds.displayRGBColor('background', default_bg_color[0], default_bg_color[1], default_bg_color[2])
            cmds.displayRGBColor('backgroundTop', default_bgTop_color[0], default_bgTop_color[1], default_bgTop_color[2])
            cmds.displayRGBColor('backgroundBottom', default_bgBtm_color[0], default_bgBtm_color[1], default_bgBtm_color[2])

            ## Set appropriate "SHOW" to modelPanel back...
            cmds.modelEditor(model_panel, edit = True, useDefaultMaterial = False, displayTextures = False, displayAppearance = 'smoothShaded', activeOnly = False)

            ## Set lambert1 to default
            cmds.setAttr("lambert1.color", 0.5, 0.5, 0.5, type = 'double3')
            cmds.setAttr("lambert1.transparency", 0, 0, 0, type = 'double3')
            cmds.setAttr("lambert1.ambientColor", 0, 0, 0, type = 'double3')
            cmds.setAttr("lambert1.incandescence", 0, 0, 0, type = 'double3')
            cmds.setAttr("lambert1.diffuse", 0.8)
            cmds.setAttr("lambert1.translucence", 0)
            cmds.setAttr("lambert1.translucenceDepth", 0.5)
            cmds.setAttr("lambert1.translucenceFocus", 0.5)

            ## Set ocean shader to default color
            if not cmds.isConnected('ocean_dispShader.outColor', 'oceanPreviewPlane_heightF.color'):
                cmds.connectAttr('ocean_dispShader.outColor', 'oceanPreviewPlane_heightF.color', force = True)

            ## Finally after render, register publish to shotgun...
            self._register_publish(publish_path,
                                   group_name,
                                   sg_task,
                                   publish_version,
                                   tank_type,
                                   comment,
                                   thumbnail_path,
                                   [primary_publish_path])
            print 'Successfully rendered nParticles Splashes to %s...' % os.path.join(publish_path, epShotName).replace('\\', '/')
            print '=================================================='
Example #41
0
def build():
    ik_node = cmds.createNode('rkt_ikSplineSolver')
    controls = cmds.createNode('transform', name='controls')
    c1_grp = cmds.createNode('transform', name='con1_grp', parent=controls)
    c2_grp = cmds.createNode('transform', name='con2_grp', parent=controls)
    c3_grp = cmds.createNode('transform', name='con3_grp', parent=controls)

    control_1 = _con('base_ctrl')
    cmds.parent(control_1, c1_grp)
    control_2 = _con('mid_ctrl')
    cmds.parent(control_2, c2_grp)
    control_3 = _con('top_ctrl')
    cmds.parent(control_3, c3_grp)

    cmds.setAttr('{}.rz'.format(c1_grp), 90)
    cmds.setAttr('{}.rz'.format(c2_grp), 90)
    cmds.setAttr('{}.rz'.format(c3_grp), 90)
    cmds.setAttr('{}.ty'.format(c2_grp), 4)
    cmds.setAttr('{}.ty'.format(c3_grp), 8)

    cmds.connectAttr('{}.worldMatrix[0]'.format(control_1),
                     '{}.inSplinePoint[0].matrix'.format(ik_node))
    cmds.connectAttr('{}.worldMatrix[0]'.format(control_2),
                     '{}.inSplinePoint[1].matrix'.format(ik_node))
    cmds.connectAttr('{}.worldMatrix[0]'.format(control_3),
                     '{}.inSplinePoint[2].matrix'.format(ik_node))

    cmds.addAttr(control_1, ln='outTangent', at='float', dv=1, keyable=True)
    cmds.addAttr(control_2, ln='inTangent', at='float', dv=1, keyable=True)
    cmds.addAttr(control_2, ln='outTangent', at='float', dv=1, keyable=True)
    cmds.addAttr(control_3, ln='inTangent', at='float', dv=1, keyable=True)

    cmds.connectAttr('{}.outTangent'.format(control_1),
                     '{}.inSplinePoint[0].tangentOut'.format(ik_node))
    cmds.connectAttr('{}.inTangent'.format(control_2),
                     '{}.inSplinePoint[1].tangentIn'.format(ik_node))
    cmds.connectAttr('{}.outTangent'.format(control_2),
                     '{}.inSplinePoint[1].tangentOut'.format(ik_node))
    cmds.connectAttr('{}.inTangent'.format(control_3),
                     '{}.inSplinePoint[2].tangentIn'.format(ik_node))

    samples = 9
    cmds.setAttr('{}.length'.format(ik_node), 10)
    cmds.setAttr('{}.samples'.format(ik_node), samples)
    skel_grp = cmds.createNode('transform', name='skeleton')
    joints = list()
    for x in xrange(samples):
        joint_obj = cmds.createNode('joint', parent=skel_grp)
        cmds.connectAttr('{}.outSRT[{}].outTranslate'.format(ik_node, x),
                         '{}.translate'.format(joint_obj))
        cmds.connectAttr('{}.outSRT[{}].outRotate'.format(ik_node, x),
                         '{}.rotate'.format(joint_obj))
        joints.append(joint_obj)

    cube = cmds.polyCube(sh=samples * 2, h=samples + 2)[0]
    cmds.setAttr("{}.overrideEnabled".format(cube), 1)
    cmds.setAttr("{}.overrideDisplayType".format(cube), 2)
    cmds.setAttr('{}.ty'.format(cube), 5)
    cmds.skinCluster(joints, cube)
    cmds.setAttr('{}.v'.format(skel_grp), False)

    xshader = cmds.shadingNode('lambert', asShader=True, name='xRed')
    cmds.setAttr('{}.color'.format(xshader), 1, 0, 0)
    yshader = cmds.shadingNode('lambert', asShader=True, name='yGreen')
    cmds.setAttr('{}.color'.format(yshader), 0, 1, 0)
    zshader = cmds.shadingNode('lambert', asShader=True, name='zBlue')
    cmds.setAttr('{}.color'.format(zshader), 0, 0, 1)

    for f in xrange(cmds.polyEvaluate(cube, f=True)):
        face = '{}.f[{}]'.format(cube, f)
        normal = [
            float(x) for x in cmds.polyInfo(face, fn=True)[0].split(':')[-1]
            [1:-2].split(' ')
        ]
        shader = xshader
        if normal[1]:
            shader = yshader
        elif normal[2]:
            shader = zshader

        cmds.select(face)
        cmds.hyperShade(assign=shader)
    cmds.select(clear=True)
    cmds.displaySmoothness(cube, polygonObject=3)
    cmds.connectAttr('{}.worldInverseMatrix[0]'.format(skel_grp),
                     '{}.parentInverseMatrix'.format(ik_node))