Ejemplo n.º 1
0
	def create_module(self, moduleType):
		# new module dialog
		moduleName, ok = QtGui.QInputDialog().getText(self, 'Add ' + moduleType + ' Module', 'Enter module name:', QtGui.QLineEdit.Normal, moduleType)

		if ok and moduleName != "":

			# If module with name is exist
			if cmds.objExists(moduleName+":main"):
				QtGui.QMessageBox.information(self, "Warning", "This module is exist.")
			else:
				# add module to list
				item = QtGui.QListWidgetItem(moduleName)
				self.modules_listWidget.addItem(item)
				self.modules_listWidget.setCurrentItem(item)
				
				# import module  
				cmds.file("G:/Projects New/AnimaCord/pk_rig/%s/%s_rig.mb" %(moduleType,moduleType), r=True, type="mayaBinary", namespace=moduleName)
				cmds.file("G:/Projects New/AnimaCord/pk_rig/%s/%s_rig.mb" %(moduleType,moduleType), importReference=True )
				cmds.parent(moduleName+":main", characterRoot)
				
				# set module name
				cmds.setAttr(moduleName+":main.moduleName", moduleName, type="string")
				
				cmds.hide(moduleName+":controls")
				cmds.select(moduleName+":main_poser")
				
				self.update_modules_list()
Ejemplo n.º 2
0
 def setAttributes(self, shader):
     self.setPreset(self.getPreference('Preset'))
     cmds.setAttr('defaultRenderGlobals.ren', 'turtle', type='string')
     cmds.setAttr('TurtleRenderOptions.renderer', 1)
     for key, value in shader.shaderAttr.iteritems():
         cmds.setAttr(getattr(self, shader.mode.lower()) + '.' + key, value)
     cmds.setAttr('TurtleDefaultBakeLayer.tbBilinearFilter',
                  self.renderAttr['tbBilinearFilter'])
     cmds.setAttr('TurtleDefaultBakeLayer.tbEdgeDilation',
                  self.renderAttr['tbEdgeDilation'])
     cmds.setAttr('TurtleDefaultBakeLayer.tbDirectory',
                  self.renderAttr['tbDirectory'],
                  type='string')
     if shader.mode == 'THICK':
         # Isolate meshes because there is a bug with Thickness when object penetrate each others
         faces = [x for x in shader.assignation if '.' in x]
         if faces:
             cmds.select(faces)
             mel.eval("InvertSelection")
             cmds.delete(
             )  # Delete and hide, or assign surfaceshader black if 'OCC'?
         toHide = list(
             set(cmds.ls(geometry=True, long=True)) - set(shader.shapes))
         if toHide:
             cmds.hide(toHide)
     elif shader.mode == 'RGB':
         try:
             attr = cmds.getAttr(shader.name + '.color')
         except ValueError:
             attr = cmds.getAttr(shader.name + '.outColor')
         cmds.setAttr(self.rgb + '.outColor', *attr[0], type='double3')
Ejemplo n.º 3
0
def nClothwInputMesh():
    mesh = cmds.ls(selection=True)[0]
    dup_mesh = cmds.duplicate(mesh)
    mesh_parent = cmds.listRelatives(parent=True, fullPath=True)

    all_nodes = cmds.ls()
    mel.eval('doCreateNCloth 0')
    new_nodes = cmds.ls()
    diff = list(set(new_nodes) - set(all_nodes))

    # Rename initial mesh to have suffix _inMesh and output mesh with _outMesh
    cmds.rename(mesh, "{}_inMesh".format(mesh))
    cmds.rename(dup_mesh[0], "{}_outMesh".format(mesh))

    # Sets the inMesh shape as the inputMesh for the nCloth node
    cmds.listConnections("{}.inputMesh".format(diff[1]), shapes=True)
    cmds.connectAttr("{}_inMeshShape.worldMesh".format(mesh),
                     "{}.inputMesh".format(diff[1]),
                     force=True)

    # Renames the nCloth node to the mesh name + _nCloth
    nCloth = cmds.rename(diff[1], "{}_nCloth".format(mesh))

    # groups the nCloth node, inMesh, and outMesh, and parents them where the inMesh was before
    cmds.group("{}_nCloth".format(mesh),
               "{}_inMesh".format(mesh),
               "{}_outMesh".format(mesh),
               name=mesh)
    cmds.parent(mesh, mesh_parent)
    # hides the initial mesh
    cmds.hide("{}_inMesh".format(mesh))
Ejemplo n.º 4
0
    def objectLoad(self):
        global grpTemp
        grpTemp = '___tmp___'

        if self.assetQList.currentItem():
            mel.eval('MLdeleteUnused;')
            cmds.file(sceneFullPath,
                      i=True,
                      gr=True,
                      dns=False,
                      gn=grpTemp,
                      ifr=True)
            cmds.select(grpTemp + '*')
            cmds.hide(grpTemp + '*')
            #mel.eval('setAttr ___tmp___.hiddenInOutliner true;AEdagNodeCommonRefreshOutliners();')
            objectList = cmds.listRelatives(grpTemp, s=False)
            objectList.sort()
            self.objectQList.addItems(objectList)
            self.objectViewCheckbox.setEnabled(True)
        else:
            self.statusBar.setStyleSheet('background-color:' + red)
            self.statusBar.showMessage('No object selected', 4000)

        self.objectListBtn.setEnabled(False)
        self.objectListClearBtn.setEnabled(True)
Ejemplo n.º 5
0
 def setAttributes(self, shader):
     self.setPreset(self.getPreference('Preset'))
     cmds.setAttr('defaultRenderGlobals.ren', 'turtle', type='string')
     cmds.setAttr('TurtleRenderOptions.renderer', 1)
     for key, value in shader.shaderAttr.iteritems():
         cmds.setAttr(getattr(self, shader.mode.lower()) + '.' + key, value)
     cmds.setAttr('TurtleDefaultBakeLayer.tbBilinearFilter', self.renderAttr['tbBilinearFilter'])
     cmds.setAttr('TurtleDefaultBakeLayer.tbEdgeDilation', self.renderAttr['tbEdgeDilation'])
     cmds.setAttr('TurtleDefaultBakeLayer.tbDirectory', self.renderAttr['tbDirectory'], type='string')
     if shader.mode == 'THICK':
         # Isolate meshes because there is a bug with Thickness when object penetrate each others
         faces = [x for x in shader.assignation if '.' in x]
         if faces:
             cmds.select(faces)
             mel.eval("InvertSelection")
             cmds.delete() # Delete and hide, or assign surfaceshader black if 'OCC'?
         toHide = list(set(cmds.ls(geometry=True, long=True)) - set(shader.shapes))
         if toHide:
             cmds.hide(toHide)
     elif shader.mode == 'RGB':
         try:
             attr = cmds.getAttr(shader.name + '.color')
         except ValueError:
             attr = cmds.getAttr(shader.name + '.outColor')
         cmds.setAttr(self.rgb + '.outColor', *attr[0], type='double3')
Ejemplo n.º 6
0
 def creatIKHendle(self, Joint1, Joint2):
     IKHendleName = mc.ikHandle(sol='ikRPsolver',
                                sj=Joint1,
                                ee=Joint2,
                                n=Joint1 + '_' + Joint2 + '_ikHandle')[0]
     mc.hide(IKHendleName)
     return IKHendleName
Ejemplo n.º 7
0
def buildRiders(pfx, spline, numJoints):
    # make the joints (or locators?)
    # just make them at origin. The constraint will put them in place
    jPars = []
    joints = []
    for i in range(numJoints):
        jp = cmds.spaceLocator(
            name="{}JointPar_{}".format(pfx, i + 1))[0]  # just for viewing
        cmds.setAttr("{}Shape.localScaleX".format(jp), 0.25)
        cmds.setAttr("{}Shape.localScaleY".format(jp), 0.25)
        cmds.setAttr("{}Shape.localScaleZ".format(jp), 0.25)
        j = cmds.createNode("joint", name="{}Joint_{}".format(pfx, i + 1))
        cmds.parent(j, jp)
        jPars.append(jp)
        joints.append(j)

    cmds.hide(joints)

    # build the constraint object
    rider = cmds.createNode("riderConstraint")

    # connect the constraints
    cmds.connectAttr("{}.outputSpline".format(spline),
                     "{}.inputSplines[0].spline".format(rider))
    for i in range(len(jPars)):
        cmds.setAttr("{0}.param[{1}]".format(rider, i), i / (numJoints - 1.0))
        cmds.connectAttr("{0}.outputs[{1}].translate".format(rider, i),
                         "{}.translate".format(jPars[i]))
        cmds.connectAttr("{0}.outputs[{1}].rotate".format(rider, i),
                         "{}.rotate".format(jPars[i]))
        cmds.connectAttr("{0}.outputs[{1}].scale".format(rider, i),
                         "{}.scale".format(jPars[i]))

    return jPars, joints
	def ResetTranslationManipsUsed( self ):
		self.NumTranslationManipsUsed 	= 0
		
		# .. se hacen invisible los que hay creados ...
		for manip in self.TranslationManips:
			manip.DestroyTranslationScriptJobs()
			cmds.hide( manip.GetGizmo() )
Ejemplo n.º 9
0
    def setUp(self):
        self.targetMesh = 'testMesh' 
        self.numVerts = 169 # number of verts in our mesh
        self.mll = MllInterface()
        
        unittest.TestCase.setUp(self)
        openMayaFile('simplemirror.ma')
        cmds.hide("|y_axis")
        cmds.showHidden("|x_axis")
    
        self.mll.setCurrentMesh(self.targetMesh)
        self.mll.initLayers()
        self.mll.createLayer("original weights")
        
        self.model = ie.LayerData()
        self.layer = ie.Layer()
        self.layer.opacity = 1.0
        self.layer.enabled = True
        self.layer.mask = [0.0]*self.numVerts
        self.layer.mask[1] = 0.9 
        self.layer.mask[5] = 0.5566 
        self.layer.name = "imported layer"
        self.model.addLayer(self.layer)

        self.infl = ie.Influence()
        self.layer.addInfluence(self.infl)
        self.infl.influenceName = "x_axis|root|R_joint1"
        self.infl.logicalIndex = 666 # use nonsense value
        self.infl.weights = [0.1]*self.numVerts
        self.infl.weights[3] = 0.688
        self.infl.weights[4] = 0.345
Ejemplo n.º 10
0
def makeHair(selList, density, layers, twist=0.0):
    if len(selList) > 1:
        firstLoop = selList
    else:
        sel = selList[0]
        cmds.select('%s.e[3]' % sel)
        cmds.polySelectSp(loop=True)
        firstLoop = cmds.ls(sl=True, fl=True)
        cmds.hide(sel)

    firstLoop = cmds.ls(cmds.polyListComponentConversion(firstLoop,
                                                         fe=True,
                                                         fv=True,
                                                         tv=True),
                        fl=True)

    # DO A LITTLE ERROR CHECKING TO SEE IF WE GOT WHAT WE NEED
    neighbor = getNeighboringEdgeloops(firstLoop)
    if len(neighbor) != len(firstLoop):
        mel.eval(
            'warning "Selected edgeloop is not a border loop. Please select a border loop and try again."'
        )
        return None

    # CREATE THE HULL CURVES
    if twist < 0:
        numIntermediates = round((twist * -1) / .1) - 1
    else:
        numIntermediates = round(twist / .1) - 1
    if numIntermediates < 0:
        numIntermediates = 0
    hullCurves = makeHullCurves(firstLoop, numIntermediates)

    twist /= numIntermediates + 1.0

    objName = firstLoop[0].split('.')[0]

    # CREATE ALL THE HAIR CURVES
    allHairCurves = []
    for i in range(layers):
        for curve in hullCurves:
            s = (i + 1) / (layers * 1.0)
            cmds.setAttr(curve + '.scale', s, s, s, type='double3')
        allHairCurves += makeHairCurves(hullCurves, density, twist)

    # DO SOME SPRING CLEANING
    cmds.delete(hullCurves)
    for i in range(len(allHairCurves)):
        curveNum = str(i + 1)
        allHairCurves[i] = cmds.rename(allHairCurves[i],
                                       '%s_%sCRV' % (objName, curveNum))

    if len(allHairCurves) > 0:
        hairGrp = cmds.rename(cmds.group(allHairCurves),
                              objName + '_hairCurves')
    else:
        mel.eval(
            'warning "No hair curves made. Perhaps Density value is too high."'
        )
Ejemplo n.º 11
0
    def build(self):
        '''
        '''
        super(Neck, self).build()
        jointList = eval(self.jointList)
        self.spline = spline.SplineBase(jointList=jointList +
                                        [self._skullBind],
                                        splineName=self._splineName)
        self.spline.create()
        grp = mc.rename(self.name, "{}_grp".format(self.name))

        # Neck
        neckNul, neckOrt, neckCtrl = control.create(name="neck",
                                                    controlType="cube",
                                                    color=common.BLUE,
                                                    hierarchy=['nul', "ort"])

        matrix = mc.xform(jointList[0], q=True, ws=True, matrix=True)
        mc.xform(neckNul, ws=True, matrix=matrix)

        # Parent the entire ik group to the neck
        mc.parent(self.spline.getGroup(), neckCtrl)

        # head
        headNul, headCtrl = control.create(name="head",
                                           controlType="cube",
                                           color=common.BLUE,
                                           hierarchy=['nul'])

        # head gimabl control
        # head
        headGimbalNul, headGimbalCtrl = control.create(name="head_gimbal",
                                                       controlType="cube",
                                                       color=common.BLUE,
                                                       hierarchy=['nul'],
                                                       parent=headCtrl)

        clusters = self.spline._clusters
        con = mc.pointConstraint(jointList[0], self._skullBind, headNul)
        mc.delete(con)
        mc.parent(headNul, neckCtrl)
        mc.parent(clusters[2:], headGimbalCtrl)
        mc.orientConstraint(headGimbalCtrl, self.spline._endTwistNul, mo=1)
        skullOffset = mc.duplicate(self._skullBind,
                                   po=True,
                                   rr=True,
                                   name="{}_offset".format(self._skullBind))[0]
        mc.parent(skullOffset, headGimbalCtrl)
        mc.orientConstraint(skullOffset, self.spline._ikJointList[-1], mo=1)
        #mc.connectAttr(headCtrl+'.s', self._skullBind+'.s')

        anchor = self.getAttributeByName('anchor').getValue()
        if mc.objExists(anchor):
            mc.parentConstraint(anchor, neckNul, mo=1)
        else:
            mc.warning('Anchor object [ {} ] does not exist.'.format(anchor))

        mc.parent(neckNul, grp)
        mc.hide(self.spline._group, clusters)
Ejemplo n.º 12
0
def extractShapes(geo, blendShape):
    bs = pm.listAttr(blendShape + '.weight', m=True)

    for shape in bs:
        cmds.setAttr(blendShape + '.' + shape, 1)
        m = cmds.duplicate(geo, n=shape)
        cmds.setAttr(blendShape + '.' + shape, 0)
        cmds.hide(m)
Ejemplo n.º 13
0
def create_fk_setup():

    selected_list = cmds.ls(selection=True)
    cmds.parent(world=True)
    dup_selected_list = cmds.duplicate(selected_list[1:], parentOnly=True)
    cmds.parent(selected_list[3], selected_list[2])
    cmds.parent(selected_list[2], selected_list[1])
    cmds.parent(selected_list[1], selected_list[0])
    renamed_list = []
    count = 1
    for item in dup_selected_list:
        new_item = cmds.rename(item, selected_list[count] + '_fk')
        renamed_list.append(new_item)
        count = count + 1
    cmds.parent(renamed_list[2], renamed_list[1])
    cmds.parent(renamed_list[1], renamed_list[0])
    cmds.parent(renamed_list[0], selected_list[0])

    cmds.select(renamed_list[0])
    cmds.hide(cmds.ls(selection=True))


    #fk ctrl

    get_name_list=[]
    for item in selected_list:
        name_split = item.split('_')
        new_name = name_split[:2]
        new_name = '_'.join(new_name)
        get_name_list.append(new_name)

    ctrl_list = []
    zro_group_list = []
    count = 0
    for jnt in renamed_list:
        ctrl = cmds.circle(r=3, nr=(1, 0, 0), n=get_name_list[count] + '_ctrl')
        ctrl_list.append(ctrl)
        cmds.matchTransform(ctrl, jnt)
        zro_group = cmds.group(em=True, n=get_name_list[count] + '_ctrl_zro')
        zro_group_list.append(zro_group)
        cmds.matchTransform(zro_group, ctrl)
        cmds.parent(ctrl, zro_group)

        cmds.setAttr(ctrl[0] + '.translateX', lock=True, keyable=False)
        cmds.setAttr(ctrl[0] + '.translateY', lock=True, keyable=False)
        cmds.setAttr(ctrl[0] + '.translateZ', lock=True, keyable=False)
        cmds.setAttr(ctrl[0] + '.scaleX', lock=True, keyable=False)
        cmds.setAttr(ctrl[0] + '.scaleY', lock=True, keyable=False)
        cmds.setAttr(ctrl[0] + '.scaleZ', lock=True, keyable=False)

        count = count + 1
        
    cmds.parent(zro_group_list[2], ctrl_list[1][0])
    cmds.parent(zro_group_list[1], ctrl_list[0][0])

    cmds.orientConstraint(ctrl_list[0][0], renamed_list[0], mo=True)
    cmds.orientConstraint(ctrl_list[1][0], renamed_list[1], mo=True)
    cmds.orientConstraint(ctrl_list[2][0], renamed_list[2], mo=True)
Ejemplo n.º 14
0
 def makePairs(self):
     sel = cmds.ls(os=1)
     garments = cmds.listRelatives(sel[0])  # len(garments)
     patterns = cmds.listRelatives(sel[1])  # len(patterns)
     retopos = cmds.listRelatives(sel[2])  # len(retopos)
     retopos_BB_width = {}
     retopos_BB_length = {}
     retopos_BB_center = {}
     patterns_BB_width = {}
     patterns_BB_length = {}
     patterns_BB_center = {}
     # In case that uv doesn't exists.
     cmds.select(retopos, r=1)
     mel.eval("performPolyAutoProj 0;")
     cmds.select(sel, r=1)
     # In case wrong bb
     for i in retopos:
         cmds.polyMergeVertex(i, d=0.001)
     # Matching
     for i in retopos:
         BB = cmds.polyEvaluate(i, b=1)
         retopos_BB_width[i] = BB[0][1] - BB[0][0]
         retopos_BB_length[i] = BB[1][1] - BB[1][0]
         retopos_BB_center[i] = [(BB[0][1] + BB[0][0]) / 2,
                                 (BB[1][1] + BB[1][0]) / 2]
     for i in patterns:
         BB = cmds.polyEvaluate(i, b=1)
         patterns_BB_width[i] = BB[0][1] - BB[0][0]
         patterns_BB_length[i] = BB[1][1] - BB[1][0]
         patterns_BB_center[i] = [(BB[0][1] + BB[0][0]) / 2,
                                  (BB[1][1] + BB[1][0]) / 2]
     pair_pattern_retopo = {}  # len(pair_pattern_retopo)
     for i in patterns:
         for j in retopos:
             if      abs(patterns_BB_width[i] - retopos_BB_width[j])         < 1 \
                 and abs(patterns_BB_length[i] - retopos_BB_length[j])       < 1 \
                 and abs(patterns_BB_center[i][0] - retopos_BB_center[j][0]) < 1 \
                 and abs(patterns_BB_center[i][1] - retopos_BB_center[j][1]) < 1:
                 pair_pattern_retopo[i] = j
     for i in pair_pattern_retopo:
         cmds.transferAttributes(i, pair_pattern_retopo[i], transferUVs=1)
     for i in pair_pattern_retopo:
         cmds.select(pair_pattern_retopo[i], i, r=1)
         cmds.CreateWrap()
     for i in pair_pattern_retopo:
         pairGarment = i[:-8]
         pattern = i
         blendObjs = [pairGarment, pattern]  # 0: target 1: origin
         blendName = cmds.blendShape(blendObjs,
                                     o='world',
                                     n='clothTransfer#')
         cmds.hide(sel[1])
         cmds.displaySurface(sel[0], x=1)
     cmds.hide(sel[1])
     cmds.displaySurface(sel[0], x=1)
     layerName = cmds.createDisplayLayer(n="garment#", e=1)
     cmds.editDisplayLayerMembers(layerName, sel[0])
     cmds.setAttr(layerName + '.displayType', 2)
Ejemplo n.º 15
0
    def createJoints(self, *args):

        # Calls to joints script to create joints
        prefix = cmds.textField(self.prefixField, query=True, text=True)
        fingerCount = cmds.intSliderGrp(self.fingerCount, q=True, v=True)
        Joints.createJoints(prefix, fingerCount)

        cmds.hide(cmds.ls(prefix + "_Loc_Grp"))
        cmds.hide(cmds.ls(prefix + "_Secondary_Loc_Grp"))
Ejemplo n.º 16
0
def hideLookdevScene(*arg):
    if cmds.objExists(grpName):
        testVis = cmds.getAttr(grpName + '.visibility')
        if testVis == True:
            cmds.hide(grpName)
        else:
            cmds.showHidden(grpName)
    else:
        pass
Ejemplo n.º 17
0
def generateSpider(input_namespace, startTime, endTime):
    '''
	this function attaches all curves together, without replacing the orignal curves, using it as a motion path
	for an animated spider. the animated spider is imported, and a simple expression links the U value of the motion
	path to a rotation attribute on the spider rig, controlling its walk cycle. there is also a custom attribute on
	the controller that appears with the spider rig, controlling the length of its steps as it walks.
	'''
    filePath = cmds.internalVar(
        usd=True
    ) + 'SpiderGen/spider.ma'  #the file path at which the spider model should exist
    fileExists = cmds.file(filePath, q=True,
                           ex=True)  #queries whether the file exists

    if fileExists is True:
        #selects all of the spiralling curves and connects them, providing a 'path' for the spiders movement.
        cmds.select(str(input_namespace) + 'curve_spiral*')
        curves = cmds.ls(selection=True)
        path = cmds.attachCurve(curves,
                                n=str(input_namespace) + 'spiderpath',
                                rpo=False)
        cmds.rebuildCurve(path, rt=3)
        cmds.hide(path)
        cmds.file(filePath, i=True)

        #renames the spider and it's callable controllers so that they are using the current 'namespace'.
        cmds.rename('SPIDER_RIG', str(input_namespace) + 'SPIDER_RIG')
        cmds.rename('SCALE_HANDLE',
                    str(input_namespace) + 'CONTROLLER_ScaleMe')
        cmds.rename('CONTROLLER', str(input_namespace) + 'CONTROLLER')

        #selects the scale controller and the path and connects them to a path animation.
        cmds.select(str(input_namespace) + 'CONTROLLER_ScaleMe', path)
        cmds.pathAnimation(stu=startTime,
                           etu=endTime,
                           f=True,
                           fa='x',
                           ua='y',
                           name=str(input_namespace) + 'motionpath')

        #creates a command that links the controller rotation to the 'length' of the animation.
        command = str(input_namespace) + 'CONTROLLER.rotateX = ' + str(
            input_namespace) + 'motionpath_uValue.output * ' + str(
                (endTime - startTime) / 10)
        #creates an expression of that command which is used for moving the legs as the spider moves around the path.
        cmds.expression(name=str(input_namespace) + 'leg_movement',
                        alwaysEvaluate=True,
                        s=command)
    else:
        #an error window for if the file is not found
        cmds.confirmDialog(
            title='Error',
            message='Spider Model not found, please ensure it located at: ' +
            str(filePath),
            button=['OK'],
            cancelButton='OK')

    return fileExists  #so that the grouping functions know not to expect the spider model or motionpath
Ejemplo n.º 18
0
def animFixShape(fixShape):
	objs=mc.ls(sl=1)
	numVtx=mc.polyEvaluate(objs[1],v=1)
	skinMeshShapes=mc.listRelatives(objs[1],s=1,pa=1)
	skinMeshShapes1=mc.listRelatives(objs[1],s=1,ni=1,pa=1)
	fixMeshShape=mc.listRelatives(objs[0],s=1,ni=1,pa=1)[0]
	inputs=mc.listHistory(objs[1])
	for i in skinMeshShapes:
		if not i in skinMeshShapes1:
			intermediateShape=i
			break
	BSNode=None
	for n in inputs:
		if 'animFixBS' in n and mc.nodeType(n)=='blendShape':
			BSNode=n
	if not BSNode:
	    BSNode=mc.blendShape(objs[1],parallel=1,n='animFixBS')[0]
	if not mc.objExists('animFixCtrl'):
		createCtrl()
		
	mc.addAttr('animFixCtrl',ln=fixShape,at='double',min=0,max=1,dv=0,k=1)
	weightAttrs=mc.listAttr(BSNode+'.weight',m=1)
	weightListNum=0
	if weightAttrs:
	    weightListNum=len(weightAttrs)
	beforeFixMesh=mc.duplicate(objs[1],n='beforeFixMesh')[0]
	buildBSMesh=mc.duplicate(objs[1],n='buildBlendShapeMesh')[0]
	mc.hide(buildBSMesh)
	buildBSMeshShapes=mc.listRelatives(buildBSMesh,s=1,pa=1)
	buildBSMeshShapes1=mc.listRelatives(buildBSMesh,s=1,ni=1,pa=1)
	for i in buildBSMeshShapes:
		if not i in buildBSMeshShapes1:
			buildBSMeshShape=i
			break
	mc.setAttr(buildBSMeshShape+'.intermediateObject',0)
	mc.delete(buildBSMeshShapes1)
	
	buildBSNode=mc.blendShape(beforeFixMesh,objs[0],buildBSMesh,foc=1,w=[(0,-1),(1,1)],n='buildFixBs')[0]
	
	mc.blendShape(BSNode,e=1,t=[objs[1],weightListNum,buildBSMesh,1])
	
	BSTargets=mc.listAttr(BSNode+'.weight',m=1)
	mc.connectAttr('animFixCtrl.'+fixShape,BSNode+'.'+BSTargets[-1])
	
	'''for i in range(0,numVtx):
		ipos=mc.xform(intermediateShape+'.vtx[%d]'%i,q=1,os=1,t=1)
		tPos=mc.xform(objs[0]+'.vtx[%d]'%i,q=1,os=1,t=1)
		bPos=mc.xform(objs[1]+'.vtx[%d]'%i,q=1,os=1,t=1)
		mc.xform(objs[0]+'.vtx[%d]'%i,os=1,t=[(ipos[0]+tPos[0]-bPos[0]),(ipos[1]+tPos[1]-bPos[1]),(ipos[2]+tPos[2]-bPos[2])])'''
	mc.delete(beforeFixMesh)
	#mc.deleteUI('animFixWin')
	mc.setAttr('animFixCtrl.'+fixShape,1)
	if not mc.objExists('targetShapesGrp'):
	    targetGrp=mc.group(em=1,n='targetShapesGrp')
	    mc.parent(targetGrp,'animFixGrp')
	shapeTmpGrp=mc.group(buildBSMesh,objs[0],n=fixShape+'_TmpGrp')
	mc.parent(shapeTmpGrp,'targetShapesGrp')
Ejemplo n.º 19
0
def _bakeObj(obj):
    '''Bake animazione.'''

    constrName = _getParentConstraint(obj)
    constrExists = cmds.ls(constrName)

    # se il constraint non esiste o non contiene keyframe esci
    if not constrExists or cmds.keyframe(constrName, q=True, kc=True) == 0:
        sys.stdout.write('Nothing to bake\n')
        return

    # primo frame
    currentFrame = cmds.currentTime(q=True)
    firstFrame = cmds.playbackOptions(q=True, ast=True)
    cmds.currentTime(firstFrame)

    # salva come lastFrame l'ultimo frame d'animazione del constraint o dell'oggetto
    keyTimes = cmds.keyframe(obj, q=True, tc=True)
    if not keyTimes:
        keyTimes = cmds.keyframe(constrName, q=True, tc=True)
    else:
        keyTimes.extend(cmds.keyframe(constrName, q=True, tc=True))
    lastFrame = max(keyTimes)

    # se all'ultimo frame rimane attached oppure il corpo e' rigido allora usa animation end time
    if max(cmds.keyframe(constrName, q=True, ev=True, t=(lastFrame, lastFrame))) > 0.0 or _getRigidBody(obj):
        lastFrame = max(lastFrame, cmds.playbackOptions(q=True, aet=True))

    # crea il locator
    locatorName = obj + _locSfx
    _setRootNamespace()
    loc = cmds.spaceLocator(n=locatorName)[0]
    cmds.hide(loc)

    # trova il parent del gruppo PH
    parent = cmds.listRelatives(_getParentHandle(obj), p=True)
    if parent:
        cmds.parent([loc, parent[0]])

    # copia l'ordine degli assi
    cmds.setAttr(loc + '.rotateOrder', cmds.getAttr(obj + '.rotateOrder'))

    # copia matrice e pivot
    cmds.xform(loc, m=cmds.xform(obj, q=True, m=True, ws=True), ws=True)
    cmds.xform(loc, piv=cmds.xform(obj, q=True, rp=True, ws=True), ws=True)

    # costringi il locator
    constraint = cmds.parentConstraint(obj, loc, mo=True)[0]

    # fai il bake
    cmds.bakeResults(loc, at=['t', 'r'], sm=True, t=(firstFrame, lastFrame), dic=True, pok=True)

    # cancella il constraint
    cmds.delete(constraint)

    # ripristina il frame precedente
    cmds.currentTime(currentFrame)
Ejemplo n.º 20
0
def setObjectAsCanvas(name):
	cmds.polyEvaluate(f=True)
	subdivSurface = cmds.polyToSubdiv(maxPolyCount=cmds.polyEvaluate(f=True), maxEdgesPerVert=32, ch=False)[0]
	liveSurface = cmds.subdToNurbs(subdivSurface, ot=0, ch=False)
	cmds.delete(subdivSurface)
	cmds.hide(liveSurface)
	cmds.makeLive(liveSurface)

	return liveSurface
Ejemplo n.º 21
0
    def toggle_hide_target(self, e=False):
        if not self.target_name:
            return

        self._is_hidden = not self._is_hidden
        if self._is_hidden:
            cmds.hide(self.imported_nodes)
        else:
            cmds.showHidden(self.imported_nodes)
Ejemplo n.º 22
0
    def render(self):
        """ Starts the render """
        try:  # If MtoA was not found
            defaultTranslator = cmds.getAttr("defaultArnoldDisplayDriver.aiTranslator")
        except ValueError:
            cmds.warning("Current renderer is not set to Arnold.")
            return

        cmds.setAttr("defaultArnoldDisplayDriver.aiTranslator", "aton", type="string")

        # Updating the port from UI
        if self.defaultPort != 0:
            port = self.portSpinBox.value()
            cmds.setAttr("defaultArnoldDisplayDriver.port", port)
        else:
            cmds.warning("Current renderer is not set to Arnold or Aton driver is not loaded.")
            return

        # Adding time changed callback
        if self.timeChangedCB == None:
            self.timeChangedCB = OM.MEventMessage.addEventCallback("timeChanged", self.timeChnaged)

        # Adding selection changed callback
        if self.selectionChangedCB == None:
            self.selectionChangedCB = OM.MEventMessage.addEventCallback("SelectionChanged", self.selectionChanged)

        try:  # If render session is not started yet
            cmds.arnoldIpr(mode="stop")
        except RuntimeError:
            pass

        # Temporary makeing hidden cameras visible before scene export
        hCams = [
            x
            for x in cmds.listCameras()
            if not cmds.getAttr("%s.visibility" % x)
            or not cmds.getAttr("%s.visibility" % cmds.listRelatives(x, s=1)[0])
        ]
        for i in hCams:
            cmds.showHidden(i)

        try:  # Start IPR
            camera = self.getCamera()
            cmds.arnoldIpr(cam=camera, mode="start")
        except RuntimeError:
            cmds.warning("Current renderer is not set to Arnold.")

        # Update IPR
        self.IPRUpdate()
        sys.stdout.write("// Info: Aton - Render started.\n")

        # Setting back to default
        for i in hCams:
            cmds.hide(i)
        cmds.setAttr("defaultArnoldDisplayDriver.aiTranslator", defaultTranslator, type="string")
        cmds.setAttr("defaultArnoldDisplayDriver.port", self.defaultPort)
Ejemplo n.º 23
0
    def build(self):
        '''
        '''
        super(Tongue, self).build()
        jointList = eval(self.jointList)
        self.spline = spline.SplineBase(jointList=jointList, splineName=self._splineName)
        self.spline.create()

        # Tongue Base
        tonugeBaseNul, tonugeBaseCtrl = control.create(name="tonuge_base", 
                                          controlType=None,
                                          color=common.RED,
                                          hierarchy=['nul'])

        matrix = mc.xform(jointList[0], q=True, ws=True, matrix=True)
        mc.xform(tonugeBaseNul, ws=True, matrix=matrix)

        # Parent the entire ik group to the neck
        mc.parent(self.spline.getGroup(), tonugeBaseCtrl) 

        # tongue Mid
        tonugeMidNul, tonugeMidCtrl = control.create(name="tonuge_mid", 
                                          controlType=None,
                                          color=common.RED,
                                          hierarchy=['nul'])

        # move the middle control between the last the middle joints
        mc.delete(mc.parentConstraint(jointList[-2], jointList[1], tonugeMidNul))

        mc.parent(tonugeMidNul, tonugeBaseCtrl) 

        # tongue Tip
        tonugeTipNul, tonugeTipCtrl = control.create(name="tonuge_tip", 
                                          controlType=None,
                                          color=common.RED,
                                          hierarchy=['nul'])

        # make the tongue tip matches the last joint in the chain
        matrix=mc.xform(jointList[-1], q=True, ws=True, matrix=True)
        mc.xform(tonugeTipNul, ws=True, matrix=matrix)

        clusters = self.spline._clusters
        mc.parent(tonugeTipNul, tonugeMidCtrl) 
        mc.parent(clusters[2:], tonugeTipCtrl)
        mc.orientConstraint(tonugeTipCtrl, self.spline._endTwistNul, mo=1)
        #mc.parentConstraint(tonugeTipCtrl, self._skullBind, mo=1)
        #mc.connectAttr(headCtrl+'.s', self._skullBind+'.s')

        anchor = self.getAttributeByName('anchor').getValue()
        if mc.objExists(anchor):
            mc.parentConstraint(anchor, tonugeBaseNul, mo=1)
        else:
            mc.warning('Anchor object [ {} ] does not exist.'.format(anchor)) 

        mc.parent(tonugeBaseNul, self.name)
        mc.hide(self.spline._group, clusters)
Ejemplo n.º 24
0
    def createMotionTrail(self, ctrls):

        cmds.waitCursor(state=True)
        self.saveTwistObjsInfo()
        self.createMainGroup()

        for loopCtrl in ctrls:
            ctrlName = self.getCtrlName(loopCtrl)
            groupNode = self.createCtrlGroup(ctrlName)

            if not groupNode: continue

            motionTrail = "%s_aTools_motionTrail" % ctrlName
            offsetNode = "%s_aTools_offset" % ctrlName
            currentLocators = [motionTrail, offsetNode]

            for loopLocator in currentLocators:
                animMod.createNull(loopLocator)
            cmds.hide(currentLocators)

            motionTrailList = self.createMotionTrailNode(offsetNode)
            motionTrailTransform = motionTrailList[0]
            motionTrailAttr = motionTrailList[1]
            motionTrailNode = motionTrailList[2]
            self.nodeInfo[ctrlName] = {
                "ctrlNode": loopCtrl,
                "offsetNode": offsetNode,
                "groupNode": groupNode,
                "motionTrailTransform": motionTrailTransform,
                "motionTrailAttr": motionTrailAttr,
                "motionTrailNode": motionTrailNode,
                "lineColor": self.lineColorCycle.next()
            }

            with G.aToolsBar.createAToolsNode:

                cmds.parent(offsetNode, motionTrail)
                cmds.parent(motionTrail, groupNode)
                cmds.parent(motionTrailTransform, groupNode)
                cmds.parent(groupNode, self.mainGroupNode)
                cmds.parentConstraint(loopCtrl, motionTrail)

            if self.offsetCtrlsPosition.has_key(ctrlName):
                offsetNodePosition = self.offsetCtrlsPosition[ctrlName][0]
                if offsetNodePosition != (0, 0, 0):
                    cmds.setAttr("%s.translate" % offsetNode,
                                 offsetNodePosition[0], offsetNodePosition[1],
                                 offsetNodePosition[2])

            self.makeDirty(ctrlName)

        cmds.select(ctrls)
        self.updateMotionTrail(lightningMode=True)
        self.updateKeysTimes()
        self.updateSortedRange()
        cmds.waitCursor(state=False)
def setShaderBall():
    shader = 'shd:shdBallShape'
    shaderSGConn = cmds.listConnections(shader,
                                        d=True,
                                        et=True,
                                        t='shadingEngine')
    sg = shaderSGConn[0]
    for geo in cmds.ls('*_GEO'):
        cmds.sets(geo, edit=True, forceElement=sg)
    cmds.hide(shader)
Ejemplo n.º 26
0
def ikHandle(name, jnt1, jnt2, parent=None):

	mc.select(jnt1, jnt2)
	ikh, eff = mc.ikHandle()
	mc.hide(ikh)
	if parent: ikh = mc.parent(ikh, parent)[0]
	ikh = mc.rename(ikh, name+"_ikh")
	eff = mc.rename(eff, name+"_eff")

	return ikh, eff
Ejemplo n.º 27
0
def hider(option, *args):
    if option == 0:
        mc.hide()
    elif option == 1:
        mc.select("*_ctrl*")
        mc.hide()
    elif option == 2:
        mc.select("*_ctrl*")
        mc.showHidden()
        mc.select(clear=True)
Ejemplo n.º 28
0
 def hide_modelDup(self):
     #self.ui2.hideModel_pushButton()
     if self.hideMD_button == 0:
         for i in self.model_dup:
             mc.hide(i)
             self.hideMD_button = self.hideMD_button + 1
     else:
         for i in self.model_dup:
             mc.showHidden(i)
             self.hideMD_button = 0
Ejemplo n.º 29
0
def doLimbsSetUp():
    initialSelecList = cmds.ls(sl=True)

    for i in initialSelecList:
        limbsSetUp(i)
       

    #++ hide Extras ++#

    cmds.hide('Extras')
Ejemplo n.º 30
0
 def hide_model(self):
     #self.ui2.hideModel_pushButton()
     if self.hideM_button == 0:
         for i in self.model:
             mc.hide(self.model)
             self.hideM_button = self.hideM_button + 1
     else:
         for i in self.model:
             mc.showHidden(self.model)
             self.hideM_button = 0
	def renderAllLights(self, renderLights=[],useGroups=False):  
		lights = cmds.ls(dag=True,visible=True,lights=True, type='mentalrayIblShape')  
		#Check if there is any lights selected to only do those
		if renderLights == [] or renderLights == None:
			renderLights = cmds.ls( dag=True,  sl=True , lights=True, type='mentalrayIblShape')
		#if there isn't any light selected just get all the lights
		if renderLights == []:
			renderLights = lights

		lightNames = ""
		for light in renderLights:
			lightNames = lightNames + light + '\n' 
				

		windowName = 'ProgressWindow'
		if cmds.window(windowName, exists=True):
			cmds.deleteUI(windowName)
			
		window = cmds.window(windowName,t="Progress Report")
		
		cmds.columnLayout()
		cmds.iconTextStaticLabel( st='textOnly', l='Rendering Lights:' )
		cmds.iconTextStaticLabel( st='textOnly', l=lightNames )
		cmds.iconTextStaticLabel( st='textOnly', l='Process Bar' )
		progressControl = cmds.progressBar(maxValue=len(renderLights), width=300)
		cmds.showWindow( window )    
		
		lights = self.sortLightsByType(lights)
		#-Revised--hide ibl node that is at the end of lights list (sorted previously)
		if cmds.objectType( lights[-1], isType='mentalrayIblShape' ) == True:
			cmds.setAttr('%s.visibleInFinalGather' % lights[-1], 0)
			cmds.setAttr('%s.visibleInEnvironment' % lights[-1], 0)
				
		cmds.hide(lights)
		lightCount = 0

		if useGroups==True:
			renderLightsGroups = self.groupLightsByName(renderLights)
			cmds.progressBar(progressControl,edit=True, maxValue=len(renderLightsGroups.keys()), width=300)
			for group in renderLightsGroups:
				self.renderOnlyThisLight(renderLightsGroups[group]) 
				progressInc = cmds.progressBar(progressControl, edit=True, pr=lightCount+1) 
				lightCount+=1
		else:
			print renderLights
			for light in renderLights:
				self.renderOnlyThisLight(light) 
				progressInc = cmds.progressBar(progressControl, edit=True, pr=lightCount+1) 
				lightCount+=1
					
		cmds.showHidden(lights)  
		#-Revised--since we sorted the lights by type we know that the lastone will be the IBL
		if cmds.objectType( lights[-1], isType='mentalrayIblShape' ) == True:
			cmds.setAttr('%s.visibleInFinalGather' % lights[-1], 1)
			cmds.setAttr('%s.visibleInEnvironment' % lights[-1], 1)
Ejemplo n.º 32
0
def build(tailRootJoint="Jt_tail", tailCurve="tail_SpIK_CV", base=None):

    tailRootCtrl = Control(prefix=removePrefix(tailRootJoint),
                           scale=8,
                           translateTo=tailRootJoint,
                           rotateTo=tailRootJoint,
                           parent=base.controlGrp,
                           lockChannels=["t", "s"])

    cmds.parentConstraint(cmds.listRelatives(tailRootJoint,
                                             p=True,
                                             type="joint")[0],
                          tailRootCtrl.Off,
                          mo=True)

    tailJoints = listJointHierarchy(tailRootJoint)
    # cluster tail curve.
    tailCurveCvs = cmds.ls(tailCurve + ".cv[*]", fl=1)
    tailCurveClusters = []

    for i in range(len(tailCurveCvs)):
        cluster = cmds.cluster(tailCurveCvs[i],
                               n=tailCurve + "_cluster%d" % i)[1]
        tailCurveClusters.append(cluster)

    cmds.parent(tailCurve, base.noTransformGrp)
    tailControls = []
    for i in range(len(tailCurveCvs)):
        ctrl = Control(prefix="tail" + "%s" % i,
                       translateTo=tailCurveClusters[i],
                       scale=3,
                       parent=base.controlGrp,
                       shape="octahedron")
        ctrl.adjustControlPosition(x=0, y=8, z=0)
        cmds.parentConstraint(tailRootCtrl.C, ctrl.Off, mo=True)
        tailControls.append(ctrl)

    for i in range(len(tailCurveCvs)):
        cmds.parent(tailCurveClusters[i], tailControls[i].C)

    tailIk = cmds.ikHandle(n=tailCurve + '_ikhandle',
                           sol='ikSplineSolver',
                           sj=tailJoints[0],
                           ee=tailJoints[-1],
                           c=tailCurve,
                           ccv=0,
                           parentCurve=0)[0]

    cmds.parent(tailIk, base.ikGrp)

    twistAt = 'twist'
    cmds.addAttr(tailControls[-1].C, ln=twistAt, k=1)
    cmds.connectAttr(tailControls[-1].C + ".%s" % twistAt, "%s.twist" % tailIk)
    cmds.hide(tailControls[0].Off)
    cmds.hide(tailCurveClusters)
Ejemplo n.º 33
0
def setGeo(sceneGeo):

    #Freeze transformations
    cmds.select(sceneGeo)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)

    #Merges objects if more than one object to catch shadows
    if len(sceneGeo) > 1:

        for obj in sceneGeo:
            noUnicode = unicode(obj)
            newObjName = noUnicode + "_mergedForShadowCatcher"
            print newObjName

        print "More than one object. Merging objects"
        cmds.select(sceneGeo)
        hideMe = cmds.polyUnite(sceneGeo, n=newObjName)
        cmds.hide(hideMe[0])
        sillyString = "connectAttr -f {}Shape.outMesh shadowCatcherShape.inMesh;".format(
            newObjName)
        #Hide the original geo in all layers

        renderlayers = cmds.ls(type="renderLayer")
        print renderlayers

        if u'default_light_rig:defaultRenderLayer' in renderlayers:
            renderlayers.remove(u'default_light_rig:defaultRenderLayer')
            print renderlayers
        """
		# for legacy render-layers setup
		for layer in renderlayers:
		    cmds.editRenderLayerGlobals( currentRenderLayer=layer )
		    cmds.hide( newObjName )  
		"""

    #otherwise do just the one
    else:
        print "Only one object selected"

        noUnicode = cmds.pickWalk(d='Down')
        noUnicode = str(noUnicode[0])

        sillyString = "connectAttr -f {}.outMesh shadowCatcherShape.inMesh;".format(
            noUnicode)
        #Hide the original geo in all layers

        renderlayers = cmds.ls(type="renderLayer")
        print renderlayers

        if u'default_light_rig:defaultRenderLayer' in renderlayers:
            renderlayers.remove(u'default_light_rig:defaultRenderLayer')
            print renderlayers

    print sillyString
    mel.eval(sillyString)
Ejemplo n.º 34
0
        def repurposeCtrls(ctrl):

            import maya.cmds as mc

            shapes = mc.listRelatives("%s_attrs" % ctrl, s=True)

            for shape in shapes:
                mc.parent(shape, ctrl, r=True, s=True)

            mc.delete("%s_attrs_orig" % ctrl)
            mc.hide("%sShape" % ctrl)
Ejemplo n.º 35
0
    def toggle_hide_source(self, e=False):
        if not cmds.ls(self.source_name):
            return

        self._is_hidden = not self._is_hidden

        if self._is_hidden:
            cmds.hide(self.source_name)
        else:
            cmds.showHidden(self.source_name)
            cmds.select(self.source_name)
Ejemplo n.º 36
0
    def resetVisiblity(self):
        """
        Hide all top level nodes within the scene. This is the default state for
        Sandwich to always hide everything before executing a render layer

        NOTE: This is only a quick solution to hide all geometries in the scene.
        We still need to iterate through each layer and hide their assigned object
        in order to be certain that the visibility remains correctly.
        """

        mc.hide(allObjects=True)
Ejemplo n.º 37
0
 def _hide(self):
     """
     Hides everything but the dynamic control.
     """
     system = cmds.listRelatives(self.pos_group, ad=True)
     for item in system:
         if not re.search("DyCtrl|DyFKCtrl", item, re.I):
             try:
                 cmds.hide(item)
             except ValueError:
                 continue
Ejemplo n.º 38
0
    def set_curves(self):
        cmds.select(self.mesh)
        # Fetching commands from mel LPC script.
        # Since now don't want to rewrite on python
        try:
            mel.eval("setDeformGeom();")
        except:
            print 'LPC not loaded. Please, initialize it.'

        a_objects = cmds.ls('*', flatten=True, transforms=True)
        cmds.select(clear=True)
        ctrl_grp = cmds.group(name=self.mesh + '_curve_ctrls', empty=True)

        for region in self.data.keys():
            locs = self.set_lpc_for_region(self.data[region])
            if region != 'excluded':
                curve_name = region + self.hi
                if self.curve_vtx_match:
                    closest_vtx = '%s.vtx[%s]' % (
                        self.mesh, str(self.curve_vtx_match[region]))
                    init_loc = self.get_init_loc(closest_vtx, locs)
                    locs = self.order_locs(locs, init=init_loc)
                else:
                    locs = self.order_locs(locs)
                hi_curve = self.create_hi_curve(locs, region)
                self.connect_locs_to_curve(locs, hi_curve)
                low_curve = self.create_low_curve(region)
                cmds.hide(hi_curve)
                cmds.wire(hi_curve,
                          w=low_curve,
                          gw=0,
                          en=1,
                          ce=0,
                          li=0,
                          dds=[(0, 100)])
                cmds.parent(low_curve, ctrl_grp)

            # Not so handful, as I expected
            # self.create_controls(low_curve)
        b_objects = cmds.ls('*', flatten=True, transforms=True)
        rig_objects = [o for o in b_objects if o not in a_objects]
        self.rig_objects = rig_objects

        if not self.curve_vtx_match:

            for c in self.data.keys():
                if c != 'excluded':
                    self.curve_vtx_match[c] = self.get_closest_vtx(
                        '%s_%s%s.cv[0]' % (self.mesh, c, self.low), self.mesh)

        func.dict_io(self.save_dir + self.current_rig + self.match_prefix +
                     self.ext,
                     self.curve_vtx_match,
                     set=True)
Ejemplo n.º 39
0
    def resetVisiblity(self):
        """
        Hide all top level nodes within the scene. This is the default state for
        Sandwich to always hide everything before executing a render layer

        NOTE: This is only a quick solution to hide all geometries in the scene.
        We still need to iterate through each layer and hide their assigned object
        in order to be certain that the visibility remains correctly.
        """

        mc.hide(allObjects = True)
Ejemplo n.º 40
0
    def __init__(self, prefix='new'):

        # global control

        super(GlobalUnit, self).__init__(prefix='superMover',
                                         curveShape='masterAnim')
        mc.parent(self.unitControl.c, self.unit)
        rigScalePlug = self.unitControl.c + '.global_scale'
        mc.addAttr(self.unitControl.c,
                   ln='global_scale',
                   at='float',
                   dv=1,
                   h=0,
                   k=1)

        for attr in self.unitControl.s:

            mc.setAttr(attr, l=0)

        mc.connectAttr(rigScalePlug, self.unitControl.c + '.sx')

        #scale reciprocal

        scaleRecip = node.recipNode(prefix='superMover',
                                    inPlugOne=rigScalePlug)
        self.recipPlug = scaleRecip + '.ox'

        # groups

        self.modelGrp = mc.group(n='model_grp', em=1)
        self.deformGrp = mc.group(n='deform_grp', em=1)
        mc.parent(self.modelGrp, self.deformGrp, self.unit)

        # clean-up

        for attr in ['t', 's', 'r']:

            mc.setAttr(self.unit + '.' + attr, l=1, cb=0, k=0)

        mc.hide(self.deformGrp)
        mc.delete(
            self.unitControl.c + 'Shape1.cv[0:10]',
            self.unitControl.off,
        )
        self.unit = mc.rename(self.unit, prefix + '_grp')
        self.unitControl.c = mc.rename(self.unitControl.c, 'superMover_ctl')

        # root control

        self.rootControl = control.Control(prefix='root',
                                           colorIdx='',
                                           curveShape='circleY',
                                           scale=0.45)
        mc.parent(self.rootControl.off, self.unitControl.c)
Ejemplo n.º 41
0
	def editSkin(self):
		if self.editSkin_button.isChecked() :
			self.mainPage_stackedWidget.setCurrentIndex(2)
			self.editCharacter_button.setChecked(False)
			self.editModules_button.setChecked(False)
			
			for m in modules:
				cmds.showHidden(m+":posers")
				cmds.hide(m+":controls")

		else:
			self.editSkin_button.setChecked(True)
Ejemplo n.º 42
0
 def showHideObjects(self, *args):
     '''
     
     '''
     if self._IScontextTool._mObjectsToHide:
         if len(self._IScontextTool._mObjectsToHide) > 0:
             
             bHide = cmds.checkBox(self._IShideObjectsCbx, query = True, value = True)
             if bHide:
                 cmds.hide(self._IScontextTool._mObjectsToHide)
             else:
                 cmds.showHidden(self._IScontextTool._mObjectsToHide)
Ejemplo n.º 43
0
def initializeRibbon(initWidth):
	mc.polyPlane(sx = 240, sy = 2.0, n = "ribbonTemp", w = initWidth, h = 0.165)
	mc.rename("polyPlane1", "ribbonTempHistory")
	mc.polySoftEdge( a = 180)
	mc.lattice( n = 'ribbon', cp = True, dv = (2, 4, 2), objectDentered = True, ldv = (2, 3, 2), outsideLattice = True )
        mc.hide()
	mc.select('ribbonTempHistory.vtx[1]', r=True )
	mc.ChamferVertex()
	mc.rename( "polyChamfer1", "tempChamfer" )
	mc.seAttr( 'tempChamfer.width', 1)
	mc.delete( 'ribbonTemp.vtx[72]' )
	return
Ejemplo n.º 44
0
def initializeBalloon(initRadius):
	mc.polySphere(sx = 12, sy = 8, n = "balloonTemp", r = initRadius)
	mc.rename( "polySphere1", "balloonTempHistory")
	mc.polySoftEdge( a = 180 )
	mc.lattice( n = 'balloon', cp = True, dv = (2, 4, 2), objectCentered = True,  ldv = (2, 3, 2), outsideLattice = True )
	mc.hide()
	mc.select('balloonTemp.vtx[84]', r=True)
	mc.ChamferVertex()
	mc.rename( "polyChamfer1", "tempChamfer" )
	mc.setAttr( 'tempChamfer.width', .1 )
	mc.delete( 'balloonTemp.f[72]' )
	return
Ejemplo n.º 45
0
 def createMotionTrailNode(self, masterNode):
     
     with G.aToolsBar.createAToolsNode: 
     
         motionTrailNode         = cmds.createNode("motionTrail", name="%s_motionTrailNode"%masterNode, skipSelect=True)
         motionTrailShape        = cmds.createNode("motionTrailShape", skipSelect=True)
         motionTrailTransform    = cmds.rename(cmds.listRelatives(motionTrailShape, parent=True)[0], "%s_motionTrailTransform"%masterNode)
         motionTrailAttr         = "%s.points"%motionTrailNode
         
         cmds.hide(motionTrailTransform)
         cmds.connectAttr("%s.worldMatrix"%masterNode, "%s.inputMatrix"%motionTrailNode, force=True)
         cmds.connectAttr("%s.points"%motionTrailNode, "%sShape.points"%motionTrailTransform, force=True)
     
     return [motionTrailTransform, motionTrailAttr, motionTrailNode]
Ejemplo n.º 46
0
 def hideUnselected(self):
     hide = True
     self.lastSelection = mc.ls(sl = 1)
     
     for obj in mc.ls(o=1, typ= "transform"):
         hide = True
         decen = mc.listRelatives(obj, ad =1)
         if decen == None:
             decen = []
         for obj2 in (decen + [obj]):
             if obj2 in self.lastSelection:
                 print obj2, obj
                 hide = False
         if hide:
             mc.hide(obj)
Ejemplo n.º 47
0
	def editModules(self):
		if self.editModules_button.isChecked() :
			self.mainPage_stackedWidget.setCurrentIndex(1)
			self.editCharacter_button.setChecked(False)
			self.editSkin_button.setChecked(False)
			
			self.update_modules_list()
			
			for m in modules:
				cmds.showHidden(m+":posers")
				cmds.hide(m+":controls")
				#cmds.setAttr(m+":skinJoints.template", 1)

		else:
			self.editModules_button.setChecked(True)
    def runScript(self):
        originalMesh = self.originalInput.text()  # Get original Mesh
        blendShapesList = []
        allBlendShapeList = []

        # List all blendshapes mesh added
        for index in xrange(self.blendList.count()):
            selectedItem = self.blendList.item(index)
            blendShapesList.append(selectedItem.text())

            # Create hierarchy
        cmds.group(em=True, name="Geometry")
        cmds.group(em=True, name="Deformers")
        cmds.group(em=True, name="Blendshapes")
        cmds.group(em=True, name="Wraps")
        cmds.parent(originalMesh, "Geometry")
        cmds.parent("Blendshapes", "Wraps", "Deformers")
        cmds.parent("Deformers", "Geometry")
        cmds.hide("Deformers")

        # Create the mirrored Blendshape mesh
        for blendShapes in blendShapesList:
            cmds.duplicate(originalMesh, name=blendShapes + "_Mirored")
            cmds.duplicate(blendShapes + "_Mirored", name=blendShapes + "_Inverted")
            cmds.blendShape(blendShapes, blendShapes + "_Inverted", name=blendShapes + "_Inverted_Node")
            cmds.select(blendShapes + "_Inverted", blendShapes + "_Mirored")
            cmds.move(10, 0, 10)
            cmds.select(blendShapes + "_Inverted")
            if self.scaleXRadio.isChecked():
                cmds.scale(-1, 1, 1)
            elif self.scaleYRadio.isChecked():
                cmds.scale(1, -1, 1)
            elif self.scaleZRadio.isChecked():
                cmds.scale(1, 1, -1)
            cmds.select(cl=True)
            self.createWrap(blendShapes + "_Inverted", blendShapes + "_Mirored")
            cmds.blendShape(blendShapes + "_Inverted_Node", edit=True, w=[(0, 1)])
            cmds.parent(blendShapes, "Blendshapes")
            cmds.parent(blendShapes + "_Mirored", "Blendshapes")
            cmds.parent(blendShapes + "_Inverted", "Blendshapes")
            cmds.hide(blendShapes + "_Inverted")
            cmds.parent(blendShapes + "_InvertedBase", "Wraps")
            allBlendShapeList.append(blendShapes)
            allBlendShapeList.append(blendShapes + "_Mirored")

            # Apply all blendshapes on the original mesh
        cmds.select(allBlendShapeList, originalMesh)
        cmds.blendShape(cmds.ls(selection=True))
Ejemplo n.º 49
0
def _fixThis(ctrl, timeRange):
    '''Fixa lo snap per questo controllo.'''

    constrName = _getParentConstraint(ctrl)
    # fixa il timerange corrente
    if timeRange:
        currentFrame = cmds.currentTime(q=True)
        allKeyTimes = list(set(cmds.keyframe(constrName, q=True, time=(cmds.playbackOptions(q=True, min=True), cmds.playbackOptions(q=True, max=True)), timeChange=True)))
        allKeyTimes.sort()
        for t in allKeyTimes:
            cmds.currentTime(t)
            _fixThis(ctrl, False)
        # ritorna al frame di prima
        cmds.currentTime(currentFrame)
    # fixa solo il frame corrente
    else:
        # se sono al primo frame o non ci sono keyframe in questo frame esci
        firstFrame = cmds.playbackOptions(q=True, ast=True)
        currentFrame = cmds.currentTime(q=True)
        if currentFrame == firstFrame or cmds.keyframe(constrName, q=True, time=(currentFrame, currentFrame), timeChange=True) == None:
            sys.stdout.write('Nothing to fix at frame %d\n' % currentFrame)
            return

        # target attivo
        activeTarget = _getActiveAttachTarget(constrName)

        # elimina le chiavi
        selectConstraintNodes(ctrl)
        cmds.cutKey(t=(currentFrame, currentFrame))

        # se rigid body rivaluta dal primo frame
        if _getRigidBody(ctrl):
            # dummy locator (faccio il bake su di lui e lo cancello)
            tempLoc = cmds.spaceLocator()[0]
            cmds.hide(tempLoc)
            # mi permette di riprodurre la simulazione dal primo frame fino a quello corrente
            cmds.bakeResults(tempLoc, at=['t'], sm=True, t=(firstFrame, currentFrame), dic=True, pok=True)
            cmds.delete(tempLoc)

        # rifai il parent (detach o attach)
        if not activeTarget:
            cmds.select(ctrl)
            detach()
        else:
            cmds.select([ctrl, activeTarget])
            attach()

        sys.stdout.write('Snap fixed at frame %d\n' % currentFrame)
Ejemplo n.º 50
0
def create_loarm_twist_setup(loarm, wrist, suffix, boneTwistAxis, reverseTwistVal=False):
    '''
    
    create_loarm_twist_setup('l_lowArm_joint', 'l_hand_joint', 'twist', 'x', reverseTwistVal=True)
    
    '''
    loArmTwist = nodeDuplicate(loarm, '%s_%s' % (loarm, suffix))
    MC.makeIdentity(loArmTwist, apply=True, scale=True)
    loArmTwistEnd = nodeDuplicate(loArmTwist, '%s_end' % loArmTwist)
    
    MC.delete(MC.pointConstraint(wrist, loArmTwist))
    MC.parent(loArmTwistEnd, loArmTwist)
    MC.parent(loArmTwist, wrist)
    
    twIkh = MC.ikHandle( n='%s_%s_ikh' % (loarm, suffix), sj=loArmTwist, ee=loArmTwistEnd, sol='ikSCsolver' )[0]
    MC.parent(twIkh, loarm)
    MC.hide(twIkh)
    
    dist = MC.getAttr('%s.t%s' % (loArmTwistEnd, boneTwistAxis))/4
    
    twJnt1 = nodeDuplicate(loArmTwist, '%s_1' % loArmTwist)
    twJnt2 = nodeDuplicate(loArmTwist, '%s_2' % loArmTwist)
    twJnt3 = nodeDuplicate(loArmTwist, '%s_3' % loArmTwist)
    
    MC.parent(twJnt1, twJnt2, twJnt3, loArmTwist)
    MC.setAttr('%s.t%s' % (twJnt1, boneTwistAxis), dist)
    MC.setAttr('%s.t%s' % (twJnt2, boneTwistAxis), dist*2)
    MC.setAttr('%s.t%s' % (twJnt3, boneTwistAxis), dist*3)
    
    twMdn = MC.createNode('multiplyDivide', name='%s_mdn' % loArmTwist)
    
    MC.connectAttr('%s.r%s' % (loArmTwist, boneTwistAxis), '%s.input1X' % twMdn)
    MC.connectAttr('%s.r%s' % (loArmTwist, boneTwistAxis), '%s.input1Y' % twMdn)
    MC.connectAttr('%s.r%s' % (loArmTwist, boneTwistAxis), '%s.input1Z' % twMdn)
    
    revVal=0
    if reverseTwistVal:
        revVal = -1
    else:
        revVal = 1
    MC.setAttr('%s.input2X' % twMdn, (.85*revVal))
    MC.setAttr('%s.input2Y' % twMdn, (.6*revVal))
    MC.setAttr('%s.input2Z' % twMdn, (.3*revVal))
    
    MC.connectAttr('%s.outputX' % twMdn, '%s.r%s' % (twJnt1, boneTwistAxis))
    MC.connectAttr('%s.outputY' % twMdn, '%s.r%s' % (twJnt2, boneTwistAxis))
    MC.connectAttr('%s.outputZ' % twMdn, '%s.r%s' % (twJnt3, boneTwistAxis))
Ejemplo n.º 51
0
 def createMotionTrail(self, ctrls):
     
     cmds.waitCursor(state=True)
     self.saveTwistObjsInfo()        
     self.createMainGroup()
     
     for loopCtrl in ctrls: 
         ctrlName                    = self.getCtrlName(loopCtrl)
         groupNode                   = self.createCtrlGroup(ctrlName)
         
         if not groupNode: continue
         
         motionTrail                 = "%s_aTools_motionTrail"%ctrlName
         offsetNode                  = "%s_aTools_offset"%ctrlName
         currentLocators             = [motionTrail, offsetNode]
         
         for loopLocator in currentLocators: animMod.createNull(loopLocator)
         cmds.hide(currentLocators)
         
         motionTrailList             = self.createMotionTrailNode(offsetNode)
         motionTrailTransform        = motionTrailList[0]
         motionTrailAttr             = motionTrailList[1]
         motionTrailNode             = motionTrailList[2]
         self.nodeInfo[ctrlName]     = {"ctrlNode":loopCtrl, "offsetNode":offsetNode, "groupNode":groupNode, "motionTrailTransform":motionTrailTransform, "motionTrailAttr":motionTrailAttr, "motionTrailNode":motionTrailNode, "lineColor":self.lineColorCycle.next()}            
         
         
         with G.aToolsBar.createAToolsNode: 
             
             cmds.parent(offsetNode, motionTrail) 
             cmds.parent(motionTrail, groupNode)
             cmds.parent(motionTrailTransform, groupNode)
             cmds.parent(groupNode, self.mainGroupNode)
             cmds.parentConstraint(loopCtrl, motionTrail)
             
         
         if self.offsetCtrlsPosition.has_key(ctrlName): 
             offsetNodePosition = self.offsetCtrlsPosition[ctrlName][0]
             if offsetNodePosition != (0,0,0): cmds.setAttr("%s.translate"%offsetNode, offsetNodePosition[0], offsetNodePosition[1], offsetNodePosition[2])
        
         self.makeDirty(ctrlName)
         
     cmds.select(ctrls)
     self.updateMotionTrail(lightningMode=True)
     self.updateKeysTimes() 
     self.updateSortedRange() 
     cmds.waitCursor(state=False)
Ejemplo n.º 52
0
def createThumbnail( mayafile  , mode = 'nonExport' ):
    if mode == 'export':
        sel = cmds.ls(sl=1 , dag=True , type = 'mesh')
        usel = cmds.ls(sl=False  )
        cmds.hide(usel)
        for x in sel:
            cmds.showHidden( x , above = True  )
    jpgfile = os.path.dirname( mayafile ) + os.sep + '.lib' + os.sep + '.'+ os.path.splitext( os.path.basename(mayafile) )[0] +'.jpg'
    currFrame = int( cmds.currentTime( q = True ) )
#     currFrame = int( (cmds.playbackOptions(q=1,min=1) + cmds.playbackOptions(q=1,max=1) ) / 2 )
    format = cmds.getAttr("defaultRenderGlobals.imageFormat")
    cmds.setAttr("defaultRenderGlobals.imageFormat", 8)
    cmds.playblast(frame=currFrame, format="image", completeFilename=str( jpgfile ), 
                   showOrnaments=False, viewer=False, widthHeight=[150, 100], percent=100 , os=1 )
    cmds.setAttr( "defaultRenderGlobals.imageFormat", format )
#     if mode == 'export' : 
#         cmds.showHidden( all = True  )        
    return jpgfile
	def renderOnlyThisLight(self, lights):

		if type(lights)!=list:
			lights = [lights]
		lightNames =''
		for light in lights:
			lightNames += '_'+cmds.listRelatives(light, p=1)[0]
			wasHidden = False
			if self.isLightHidden(light) :
				cmds.showHidden(light)
				wasHidden = True

			#-Revise!--if it is an ibl light then turn off emit Final Gather
			if cmds.objectType( light, isType='mentalrayIblShape' ) == True:
				if cmds.getAttr('%s.visibleInFinalGather' % light) == False:
					cmds.setAttr('%s.visibleInFinalGather' % light, 1)

					wasHidden = True

		mel.eval("renderIntoNewWindow render")   

		#See if we are rendering with vray frame buffer and save it to the maya render buffer
		if cmds.getAttr('defaultRenderGlobals.currentRenderer') == 'vray':
			if self.isRenderEngineInstalled('vray'):
				if cmds.getAttr ("vraySettings.vfbOn"):
					mel.eval("vrend -cloneVFB")                                              

		rv = cmds.getPanel(scriptType='renderWindowPanel')
		caption = cmds.renderWindowEditor(rv, query=True, pca=True)            
		newCaption = caption+' contriburion of '+lightNames.replace('_',' ')
		cmds.renderWindowEditor(rv, edit=True, pca= newCaption)

		# save the frame in mel
		mel.eval("renderWindowMenuCommand keepImageInRenderView renderView;")

		if self.saveImages:
			self.saveCurrentImageInRenderView('contributionOf'+lightNames)

		for light in lights:
			if wasHidden:
				cmds.hide(light)
				#-Revise!-- if it was the ibl node disable final gather again
				if cmds.objectType( light, isType='mentalrayIblShape' ) == True:
					cmds.setAttr('%s.visibleInFinalGather' % light, 0)
Ejemplo n.º 54
0
def convert_jsShoulderRigToFK():
    
    for side in ['l', 'r']:
        
        # Delete existing IK shoulder rig
        ikh = '%s_shoulder_skin_handle' % side
        if MC.objExists(ikh):
            MC.delete(ikh)
        ctrl = '%s_shoulder_anim' % side
        MC.lockNode(ctrl, lock=False)
        MC.delete(ctrl)
        
        # Duplicate shoulder skin joint to make Fk shoulder control
        shldrSkin = '%s_shoulder_skin' % side
        shldrCtrl = MC.duplicate(shldrSkin, rr=True)[0]
        MC.delete(MC.listRelatives(shldrCtrl, f=True, children=True))
        shldrCtrl = MC.rename(shldrCtrl, shldrCtrl.replace('skin1', 'anim'))
        shldrAtt = MC.duplicate(shldrCtrl, rr=True)[0]
        shldrAtt = MC.rename(shldrAtt, '%s_att' % shldrCtrl)
        MC.parent(shldrCtrl, shldrAtt)
        
        shldrEnd = MC.duplicate('%s_shoulder_end_joint' % side, rr=True)[0]
        shldrEnd = MC.rename(shldrEnd, '%s_end' % shldrCtrl)
        MC.parent(shldrEnd, shldrCtrl)
        MC.hide(shldrSkin)
        
        MC.orientConstraint(shldrCtrl, shldrSkin)
        
        ctrlHdl = MC.circle(ch=False,nr=[0,0,1],r=8)
        ctrlHdlShp = MC.listRelatives(ctrlHdl, shapes=True)
        ctrlHdlShp = MC.rename(ctrlHdlShp, '%sShape' % shldrCtrl)
        MC.parent(ctrlHdlShp, shldrCtrl, r=True, s=True)
        MC.delete(ctrlHdl)
        
        MC.select('%s.cv[0:7]' % ctrlHdlShp)
        if 'l' in side:
            MC.move(9,0,0, relative=True)
        elif 'r' in side:
            MC.move(-9,0,0, relative=True)
        
        MC.connectAttr('%s.sx' % shldrCtrl, '%s.sx' % shldrSkin)
        
        for attr in ['tx', 'ty', 'tz', 'sy', 'sz']:
            MC.setAttr('%s.%s' % (shldrCtrl, attr), lock=True, keyable=False)
Ejemplo n.º 55
0
def subCam(mainCam, camName):
    """Generate the stack of child cameras and parent
    under mainCam from the calling operation."""
    # Handheld1 - first layer of handheld motion
    cmds.camera(
        displayGateMask=True,
        filmFit='overscan',
        overscan=1.0
    )
    handCam1 = cmds.rename(camName + '_handheld_1')
    cmds.parent(handCam1, mainCam, relative=True)
    connectAtt(mainCam, handCam1)
    cmds.hide()

    # Handheld2 - second layer of handheld motion
    cmds.camera(
        displayGateMask=True,
        filmFit='overscan',
        overscan=1.0
    )
    handCam2 = cmds.rename(camName + '_handheld_2')
    cmds.parent(handCam2, handCam1, relative=True)
    connectAtt(handCam1, handCam2)

    # Shake1 - first layer of shake vibration
    cmds.camera(
        displayGateMask=True,
        filmFit='overscan',
        overscan=1.0
    )
    shakeCam1 = cmds.rename(camName + '_shake_1')
    cmds.parent(shakeCam1, handCam2, relative=True)
    connectAtt(handCam2, shakeCam1)

    # Shake2 - second layer of shake vibration
    cmds.camera(
        displayGateMask=True,
        filmFit='overscan',
        overscan=1.0
    )
    shakeCam2 = cmds.rename(camName + '_shake_2')
    cmds.parent(shakeCam2, shakeCam1, relative=True)
    connectAtt(shakeCam1, shakeCam2)
Ejemplo n.º 56
0
    def doRelease(self):
        # print "RELEASED"

        self.isMouseDown = False

        if(self.deltaFront != 0):
            app().activeDocument.document().resizeSelection(self.deltaFront)

        if(self.deltaBack != 0):
            app().activeDocument.document().resizeSelection(self.deltaBack)

        m = Mom()
        m.strandsSelected(self.helicesNames, (True, True))

        cmds.hide(helixManip.transformName)

        self.frontDistance = 0
        self.backDistance = 0

        return OpenMaya.kUnknownParameter
Ejemplo n.º 57
0
def trafficLights(street,size,daytime):
    '''
    Creates traffic lights for the city.
    
    street: An object of the class Street, which is the root node of the binary
            tree that makes up the street structure for the city.
    size: Tuple that contains the x- and z-components for the size of the city.
    daytime: Boolean variable which is true if it is day and false if it is night.
    On exit: Traffic lights polygonal objects of each type ("R", "G", "Y", "RY") have 
             been created using makeTrafficLight(...) and instances placed using 
             placeTrafficLights(...). 
              
    '''
    RedLightGeom = makeTrafficLight("R")
    RedYellowLightGeom = makeTrafficLight("RY")
    YellowLightGeom = makeTrafficLight("Y")
    GreenLightGeom = makeTrafficLight("G")
    cmds.group(RedLightGeom[0], RedYellowLightGeom[0], YellowLightGeom[0], GreenLightGeom[0], name = "trafficLights")
    placeTrafficLights(street, [RedLightGeom,RedYellowLightGeom,YellowLightGeom,GreenLightGeom], size)
    cmds.hide(RedLightGeom[0],RedYellowLightGeom[0],YellowLightGeom[0],GreenLightGeom[0])
Ejemplo n.º 58
0
    def toggleMaskActive(self, mode):
        try:
            cmds.undoInfo(openChunk=True)
            if mode:
                cmds.showHidden(self.controls)
                cmds.showHidden(self.maskGeo)

                #hide all movers
                cmds.hide(self.faceModule.jointMovers)
                #TODO: Need to check if the constraints were deleted and re-add them
                '''for mover in self.faceModule.jointMovers:
                    sdk = cmds.listConnections(mover + '.sdk')[0]
                    sdkParent = cmds.listRelatives(sdk, parent = True)[0]
                    lra = cmds.listConnections(mover + '.lra')[0]
                    cmds.parentConstraint(lra, sdkParent)'''
                print 'MASK: ACTIVATED'

            else:
                #show joint movers
                cmds.showHidden(self.faceModule.jointMovers)

                #hide the mask controls and mesh
                cmds.hide(self.controls)
                cmds.hide(self.maskGeo)
                print 'MASK: DEACTIVATED'
        except Exception as e:
            print(traceback.format_exc())
        finally:
            cmds.undoInfo(closeChunk=True)
Ejemplo n.º 59
0
def Animposecam(sel_obj):
#    if mc.objExists('poseLibCaptureCamera'):
#        mc.delete('poseLibCaptureCamera')
    if not mc.objExists('poseLibCaptureCamera'):
        CurrentPanel  = mc.getPanel(withFocus=True)
        #print CurrentPanel
        if mc.getPanel(to=CurrentPanel!= "modelPanel") :   
            visPanel  = mc.getPanel(vis=True)    
            for name in visPanel:
                modelPanels= mc.getPanel(type= 'modelPanel')    
                if mc.getPanel (to = name == "modelPanel"):
                    mc.setFocus(name)
                    CurrentPanel = name
                    break
        if mel.eval('catch(`modelPanel -q -cam %s`)'%CurrentPanel):
            CurrentCamera = "persp"
        else:
            CurrentCamera = mc.modelPanel(CurrentPanel,q=1,cam=1)
        
        campos= mc.camera(CurrentCamera,q=1,position=1)
        camrot= mc.camera(CurrentCamera,q=1,rotation=1) 
        camwup= mc.camera(CurrentCamera,q=1,worldUp =1)
        camcoi= mc.camera(CurrentCamera,q=1,coi=1)
        focal = mc.camera(CurrentCamera,q=1,fl=1) 
        camShapeNode = mc.createNode("camera")
        camTopNode   = mc.listRelatives(camShapeNode,p=1) 
        mc.rename (camTopNode[0] ,'poseLibCaptureCamera')
        mc.hide('poseLibCaptureCamera')
        focalLengthTmp = 200
        nearClipTmp = .1
        farClipTmp = 10000
        mc.camera('poseLibCaptureCamera',e=1,
                position =[campos[0],campos[1],campos[2]],
                rotation =[camrot[0],camrot[1],camrot[2]],                 
                worldUp  =[camwup[0],camwup[1],camwup[2]],
                fl = focalLengthTmp,
                nearClipPlane = nearClipTmp,
                farClipPlane = farClipTmp)
    AnimposeCreateWindow(sel_obj)
Ejemplo n.º 60
0
        def hdri_render_main(self):
            if self.current_renderer not in self.accepted_renderers:
                cmds.inViewMessage(amg="This feature currently supports Vray, Arnold or Redshift renderers only",
                                   pos="botCenter", fade=True)
                return

            if self.render_position == "object":    # will render from object(s) centre
                if not self.render_geo:
                    cmds.inViewMessage(amg="Please Select an Object from which to render HDRI View",
                                       pos="botCenter", fade=True)
                    return

                else:
                    # get averaged centre of selected objects
                    x, y, z = 0, 0, 0
                    for geo in self.render_geo:
                        xyz = cmds.objectCenter(geo)
                        x += xyz[0]
                        y += xyz[1]
                        z += xyz[2]

                    objs_centre = x / len(self.render_geo), y / len(self.render_geo), z / len(self.render_geo)
                    cmds.hide(self.render_geo)  # hide objects while rendering

            # zero out any camera rotations and reposition to objects centre if needed
            cmds.setAttr("%s.rotate" % self.render_camera, 0, 0, 0)

            if self.render_position == "object":
                cmds.setAttr("%s.translate" % self.render_camera, objs_centre[0], objs_centre[1], objs_centre[2])

            if self.current_renderer == "vray":
                self.vray_render()
            if self.current_renderer == "redshift":
                self.redshift_render()
            if self.current_renderer == "arnold":
                self.arnold_render()