예제 #1
0
def create_facial_rig():
    errmsg = []
    msg = ft.create_ctl()
    errmsg.append(msg)
    pm.refresh()
    if not pm.confirmBox(title='Facial Rig Status',message = "Face Control Created\nError:\n%s"%msg, yes='Continue?', no='Stop?'):
        return
    msg = ft.create_eye_rig()
    errmsg.append(msg)
    pm.refresh()
    if not pm.confirmBox(title='Facial Rig Status',message = "Eyeballs Rig Created\nError:\n%s"%msg, yes='Continue?', no='Stop?'):
        return
    msg = ft.connect_mouth_ctl()
    errmsg.append(msg)
    pm.refresh()
    if not pm.confirmBox(title='Facial Rig Status',message = "Mouth Control to Bone Connected\nError:\n%s"%msg, yes='Continue?', no='Stop?'):
        return
    msg = ft.create_facial_bs_ctl()
    errmsg.append(msg)
    pm.refresh()
    if not pm.confirmBox(title='Facial Rig Status',message = "Create BlendShape control and setup BlendShape \nError:\n%s"%msg, yes='Continue?', no='Stop?'):
        return
    # ft.parent_ctl_to_head()
    # pm.refresh()
    # if not pm.confirmBox(title='Facial Rig Status',message = "Parent Root Group to Head OK", yes='Continue?', no='Stop?'):
    #     return
    msg = ft.copy_facialskin()
    pm.refresh()
    if not pm.confirmBox(title='Facial Rig Status',message = "Facial Copy \nError:\n%s"%msg, yes='Continue?', no='Stop?'):
        return
    pm.informBox(title='Riggin Status', message = "Face Rig Complete")
예제 #2
0
def remove_sub_frames(obj_list):
    '''
    Sets a key on every whole frame over the keyed range of all objects, then removes all subframe keys.

    Args:
        obj_list (list<PyNode>): List of all objects to remove sub frames on
    '''
    #pm.select(None)
    #for model_panel in pm.getPanel(type='modelPanel'):
    #    pm.isolateSelect(model_panel, state=True)
    #pm.refresh(su=True)

    try:
        key_frame_list = list(set(pm.keyframe(obj_list, q=True)))
        key_frame_list.sort()
        first_keyframe = get_first_or_default(key_frame_list)
        last_keyframe = get_last_or_default(key_frame_list)

        time_range = (int(first_keyframe), int(last_keyframe))
        current_time = pm.currentTime()
        for frame in xrange(time_range[0], time_range[1] + 1):
            pm.currentTime(frame)
            pm.setKeyframe(obj_list)
    except:
        pass
    finally:
        pm.refresh(su=False)
        for model_panel in pm.getPanel(type='modelPanel'):
            pm.isolateSelect(model_panel, state=False)

    pm.currentTime(current_time)
    pm.select(obj_list, r=True)

    for frame in [x for x in key_frame_list if x % 1 > 0]:
        pm.cutKey(obj_list, t=frame)
def closestEndOrStartCVToSurface(targetSurface, transforms, locOutput=1, componentOutput=0):
	'''
	Usage:
		closestEndOrStartCVToSurface(pm.ls(sl=True)[-1], pm.ls(sl=True)[:-1], locOutput=1, componentOutput=0)
	'''
	start_time = time.time()
	# your code
	cpom = pm.createNode('closestPointOnMesh')
	targetSurface.outMesh.connect(cpom.inMesh)
	closestComponents=[]
	for transform in transforms:
		closestVert = aw_shellRig.closestPoint(pm.ls(transform.getShape().cv[:], fl=True), targetSurface)
		#now getting that vert on the original mesh
		cpom.inPosition.set(closestVert.getPosition())
		closestVertIndex = cpom.closestVertexIndex.get()
		if locOutput:
			loc = pm.spaceLocator(n=transform.name().replace('GEO','LOC'))
			loc.translate.set(targetSurface.getShape().vtx[closestVertIndex].getPosition())
			pm.refresh()
		if componentOutput:
			closestComponents.append(targetSurface.getShape().vtx[closestVertIndex])
	pm.delete(cpom)
	elapsed_time = time.time() - start_time
	print 'Finished...\nTime elapsed %02d:%02d'%(int(math.floor(elapsed_time/60.0)), int(math.floor(elapsed_time%60.0)))
	if componentOutput:
		return closestComponents
예제 #4
0
def rtb_scale_layer_mesh(highresListDropdown, *args, **kwargs):
  ''' '''
  global defaultString
  scale = pm.floatSlider(prefix+'_floatSlider_layer_mesh', query=True, value=True)
  scale = math.pow(scale,2)  #makes the slider a bit progressive, gives a better feel to the scale in the low range
  scale = 1+scale*5  #remaps 0-1 to 1-6

  #iterate over the entire list and adjust scales
  currentItem = highresListDropdown.getSelect()
  numItems = highresListDropdown.getNumberOfItems()

  for item in range(numItems):
    item = item+1
    if item > 1:
      highresListDropdown.setSelect(item)

      high = highresListDropdown.getValue()

      if not high == defaultString:
        high = pm.PyNode(high.split("'")[0]) #get rid of unicode crap        
        high.setScale([scale, scale, scale])

  #return list selection to original
  highresListDropdown.setSelect(currentItem)

  #force a viewport refresh
  pm.refresh()
예제 #5
0
파일: limb.py 프로젝트: pritishd/PKD_Tools
    def buildControl(self):
        if not self.mainIK:
            self.mainIK = self.createCtrlObj(self.part)
            self.mainIK.lockScale()
            self.alignControl()
            self.mainIK.addChild(self.ikHandle.SUP_Prnt.pynode)

        # Is it a spring solver
        # Adding control control the spring solver
        if self.ikSolver == "ikSpringSolver":
            pm.refresh()
            ikHandle = pm.PyNode(self.ikHandle.mNode)
            if hasattr(ikHandle, "springAngleBias"):
                springAngleBias = ikHandle.springAngleBias
                numBias = springAngleBias.numElements()

                self.springBiasCtrl.addDivAttr("SpringBias", "lblSpringBias")
                self.springBiasCtrl.addFloatAttr("Start", sn="StartBias", dv=0.5)
                self.springBiasCtrl.pynode.StartBias >> springAngleBias[0].springAngleBias_FloatValue

                if numBias > 2:
                    for i in range(1, numBias - 1):
                        attr = "MidBias{}".format(i)
                        self.springBiasCtrl.addFloatAttr("Mid{}".format(i), sn=attr, dv=0.5)
                        self.springBiasCtrl.pynode.attr(attr) >> springAngleBias[i].springAngleBias_FloatValue

                self.springBiasCtrl.addFloatAttr("End", sn="EndBias", dv=0.5)
                self.springBiasCtrl.pynode.EndBias >> springAngleBias[numBias - 1].springAngleBias_FloatValue
            else:
                print "Could not find srpingAngleBias in {}".format(self.ikHandle.pynode)

        else:
            pass
예제 #6
0
    def space_switcher(self, index, start_frame, end_frame, key_switch):
        # Temporary disable cycle checks during swapping
        cycle_check = pm.cycleCheck(q=True, e=True)
        pm.cycleCheck(e=False)
        autokey_state = pm.autoKeyframe(q=True, state=True)
        pm.autoKeyframe(state=False)

        try:
            # Disable viewport refresh to speed up execution
            pm.refresh(su=True)

            pm.currentTime(start_frame)
            current_space = self.get_current_space()
            if current_space != None:
                control = self.network['controls'].get_first_connection()
                matrix_list = maya_utils.baking.get_bake_values([control], start_frame, end_frame)
            
                self.swap_space(index, current_space, start_frame, key_switch)
                self.swap_space(current_space, index, end_frame, key_switch, end_cap = True)

                maya_utils.baking.space_switch_bake([control], start_frame, end_frame, matrix_list)

            pm.currentTime(start_frame)
        except Exception, e:
            exception_info = sys.exc_info()
            v1_core.exceptions.except_hook(exception_info[0], exception_info[1], exception_info[2])
예제 #7
0
 def reloadTextureList(cls, texList, *args, **kwargs):
   ''' reloads a list of texture nodes '''
   for item in texList:
     path = pm.getAttr(item+'.fileTextureName')
     if os.path.exists(path):
       pm.setAttr(item+'.fileTextureName',path)
   pm.refresh()
예제 #8
0
 def press_cmd(self, *args) :
     
     ctx            = self.ctx
     print "paramProgress_befor", self.paramProgress_befor
     
     pressPosition              = cmds.draggerContext( ctx, query=True, anchorPoint=True)
     self.drag_star_point       = pressPosition
     print ("Press: " + str(pressPosition))
     
     #self.paramProgress = 0.0
     pos            = curvetool.getCurvePoint(
                             self.cur,
                             [self.paramProgress],
                             "normal"
                             )[0]   
                     # 第二引数でターゲットの初期位置を指定
     
     self.moving_sph       = pm.sphere(n = "moving_sph", r=0.1)[0]
     pm.move( self.moving_sph , [pos[0],pos[1],pos[2]] )
     pm.refresh(f = 1)
     
     # ハイライト
     pm.hilite(self.cur)
     list = pm.ls(type = u'transform')
     for i in list :
         if "temp" in i.name() :
             pm.hilite(i)
예제 #9
0
def ar_displayMessage(status, message):
    """
    display message with different color in maya according to status.
    :param status: string
    :param message: string
    :return: message
    """
    # exit if this function run in batch mode.
    if pm.about(batch=True):
        return False
    # Base color    Text Color.
    statusColors = {
        'error': ((255, 40, 20), (0, 0, 0)),
        'warning': ((255, 177, 86), (0, 0, 0)),
        'success': ((140, 230, 140), (0, 0, 0))
    }
    # commandLine1 will be unique in maya in all cases.
    commandLinePtr = omui.MQtUtil.findControl('commandLine1')
    commandLine = wrapInstance(long(commandLinePtr), QtGui.QWidget)
    # get result Line.
    resultLine = commandLine.findChildren(QtGui.QLineEdit)[0]
    palette = resultLine.palette()
    palette.setBrush(QtGui.QPalette.Base,
                     QtGui.QColor(*statusColors[status][0]))
    palette.setColor(QtGui.QPalette.Text,
                     QtGui.QColor(*statusColors[status][1]))
    resultLine.setPalette(palette)
    resultLine.setText('[ ' + status + ' ] ' + message)
    pm.refresh()
예제 #10
0
def copySkinWeights(*args):
    '''
    스킨 웨이트를 여러 오브젝트에 옮겨줌
    디폴트 스킨이 적용된 여러 오브젝트를 먼저 선택한 후, 스키닝 데이터가 적용된 메쉬를 제일 마지막에 선택, 실행해줌.
    옵션은 마야 CopySkinWeightsOptions 세팅을 따름.
    '''
    if args:
        pm.select( args )
    sel = cmds.ls(sl=True, fl=True )
    if len(sel)<2 : return

    geos = sel[:-1]
    skinMesh = sel[-1]

    failedGeo = []
    for geo in geos:
        try:
            pm.select(skinMesh, geo)
            pm.mel.CopySkinWeights()
            pm.refresh()

            print '#--------------------------------------'
            print '#'
            print '#  copy weight (Success): "%s" --> "%s"'%(skinMesh, geo)
            print '#'
            print '#--------------------------------------'
        except:
            failedGeo.append(geo)
            print '#  copy weight (Fail) : "%s" --> "%s"'%(skinMesh, geo)

    if failedGeo:
        print 'failedGeo = ', failedGeo
        pm.select(failedGeo)
def rtb_scale_layer_mesh(highresListDropdown, *args, **kwargs):
    ''' '''
    global defaultString
    scale = pm.floatSlider(prefix + '_floatSlider_layer_mesh',
                           query=True,
                           value=True)
    scale = math.pow(
        scale, 2
    )  #makes the slider a bit progressive, gives a better feel to the scale in the low range
    scale = 1 + scale * 5  #remaps 0-1 to 1-6

    #iterate over the entire list and adjust scales
    currentItem = highresListDropdown.getSelect()
    numItems = highresListDropdown.getNumberOfItems()

    for item in range(numItems):
        item = item + 1
        if item > 1:
            highresListDropdown.setSelect(item)

            high = highresListDropdown.getValue()

            if not high == defaultString:
                high = pm.PyNode(high.split("'")[0])  #get rid of unicode crap
                high.setScale([scale, scale, scale])

    #return list selection to original
    highresListDropdown.setSelect(currentItem)

    #force a viewport refresh
    pm.refresh()
예제 #12
0
def applyNodePositions(matrices, nodes):
    '''
    Applies the the given matrices to the given nodes in world space.

    Has some smarts for applying differing number of matrices to nodes.
    Ex:
        1 matrix, many nodes: All nodes are set to this matrix
        3 matrices, 2 nodes: First two matrices are applied.
        2 matrices, 3 nodes: IndexError is raised due to ambiguous case.
        3 matrices, 3 nodes: All three positions are applied.
    '''

    # Stop undo, so this doesn't get annoying for artist
    with internal.UndoChunk(), internal.MaintainSelection():

        # create temporary group outside of loop
        positionGroup = pm.group(n='mmo_applyPos_tmpGrp', em=1)

        # If passed a string instead of a list
        if isinstance(nodes, basestring):
            nodes = [nodes]

        # Make number of matrices match nodes
        if len(matrices) != len(nodes):

            # Much like GoodParenting, we allow 1 position to be applied to
            # multiple nodes. We also allow a partial application of matrices,
            # when there are more matrices passed than nodes.
            # The only case we can't handle, is when there are otherwise less
            # matrices than nodes.  It's ambiguous what to do if 2 matrices
            # were to be applied to 3 nodes.
            if len(matrices) == 1:
                matrices = matrices * len(nodes)  # Copy list
            elif len(nodes) > len(matrices):
                raise IndexError('More nodes (%d) than saved matrices (%d)!' %
                                 (len(nodes), len(matrices)))

        for matrix, node in zip(matrices, nodes):
            if not isinstance(node, pm.PyNode):
                node = pm.PyNode(node)
            # Don't constraint directly to selected, since it could be
            # something special or have stuff locked.  Create a duplicate of
            # selected group, and constrain that
            positionGroup.setMatrix(matrix, worldSpace=True)
            dummyGroup = duplicateGroup(node, 'mmo_applyPosDummy_tmpGrp')
            tempConst = pm.parentConstraint(positionGroup, dummyGroup)
            pm.refresh()

            # Copy attributes from the dummy group onto the real one.
            for attr in 'tx ty tz rx ry rz sx sy sz'.split():
                value = dummyGroup.getAttr(attr)
                try:
                    node.setAttr(attr, value)
                except RuntimeError:
                    _log.warning('Could not set value for %s.%s, skipping...',
                                 node, attr)

            pm.delete(tempConst)
            pm.delete(dummyGroup)
        pm.delete(positionGroup)
예제 #13
0
    def process(self, instance):

        rs = renderSetup.instance()
        master_layer = rs.getDefaultRenderLayer()
        rs.switchToLayer(master_layer)

        self.log.info("SCENE SAVE")

        if instance.context.data.get('ftrackData'):
            if instance.context.data['ftrackData']['Project']['code'] == 'hbt':
                self.log.info("Switching texures to PROXY")
                import hbt_switch_tex as hbtSw
                reload(hbtSw)

                nhbtData=hbtSw.switchTexture()

                nhbtData.option = 2
                nhbtData.highest = False
                nhbtData.limit = 1600
                nhbtData.validatorCheck()
                nhbtData.fast = False

                nhbtData.all = True
                nhbtData.switch()
                pm.refresh(f = True)

                self.log.info("Switched to PROXY before save")

        self.log.info('saving scene')
        maya.cmds.file(s=True)
예제 #14
0
def lcBake_convert_lightmap(bakeSetListDropdown, cameraListDropdown, *args, **kwargs):
  ''' '''
  numItems = bakeSetListDropdown.getNumberOfItems()
  if numItems > 0:
    currentBakeSet = bakeSetListDropdown.getValue()
    if currentBakeSet:
      currentCamera = cameraListDropdown.getValue()
      outputDirectory = pm.textField(prefix+'_textField_texture_path', query=True, text=True)      
      if os.path.exists(outputDirectory):
        shadows = pm.checkBox(prefix+'_checkBox_shadows', query=True, value=True)
        
        if pm.control('bakeWindow', exists = True):
          pm.deleteUI('bakeWindow')          
        bakeWindow = pm.window('bakeWindow', t='Batch Bake', widthHeight=[100, 100], rtf=True, mnb=False, mxb=False, s=False)
        pm.columnLayout()
        pm.text(l='')
        pm.text(l='')
        pm.text(l='          Bake In Progress          ')
        pm.text(l='                  ......        ')
        pm.text(l='')
        pm.text(l='')
        bakeWindow.show()
        pm.refresh()
        #pm.pause(seconds=10)
        
        convertString = bake.convertLightmap(currentBakeSet, currentCamera, outputDirectory, shadows)
        
        print('Convert Command: {0}'.format(convertString) )
                
        pm.deleteUI('bakeWindow')    
        
        pm.select(clear=True)
      else:
        pm.warning('Path not found: {0}'.format(outputDirectory) )
def run():
    defaultRenderGlobal = pm.PyNode('defaultRenderGlobals')
    begin = defaultRenderGlobal.startFrame.get()
    end =defaultRenderGlobal.endFrame.get()

    mainprocess = pm.mel.eval('$tmp = $gMainProgressBar')
    pm.progressBar(mainprocess,
                   edit=True,
                   beginProgress=True,
                   isInterruptable=True,
                   status='Rendering in foreground ...',
                   minValue = int(begin),
                   maxValue=int(end))

    for x in range(int(begin), int(end)+2):
        if pm.progressBar(mainprocess, q=True, ic=True):
            break

        pm.progressBar(mainprocess, e=True, step=1)
        pm.currentTime(x)
        pm.arnoldRender(b=True, seq=str(x))
        pm.refresh()
    pm.progressBar(mainprocess,
                   edit=True,
                   endProgress=True,
                   )
    pm.warning('BatchRender activeRenderLayer complete!')
예제 #16
0
 def get_data_file(self, *args, **kwargs):
     '''
     get obj data from an obj file
     '''
     if self.objPath:
         # add path exists check
         if os.path.splitext(self.objName)[1].lower() == '.obj':
             if self.verbose:
                 lcUtility.Utility.lc_print('{} loading: {}'.format(self.notation, self.objPath))
                 pm.refresh()
             for i, line in enumerate(open(self.objPath, "r")):
                 if line.startswith('#') and not line.startswith('#MRGB'):
                     self.comments.append(line.rstrip('\n'))
                 elif line.split(' ')[0] == 'v':
                     values = line.split()
                     if values:
                         self.v.append(map(float, values[1:4]))
                 elif line.startswith('#MRGB'):
                     # zbrush mrgb notation is MMRRGGBB for each vert stacked in lines of up to 64
                     line = line[6:]  # remove '#MRGB ' from begining of line
                     self.mrgb.extend(re.findall('........', line))
                 elif line.startswith('g'):
                     self.g.append(line.split()[1])
                 else:
                     # if not 'g default' in line:
                     self.remainder.append(line.rstrip('\n'))
     else:
         lcUtility.Utility.lc_print('obj path not set')
예제 #17
0
    def export_hierarchy_obj(self):
        """Export the individual meshes in the hierarchy"""
        file_info = {}
        # Reverse the geo list so that the deepest geo is deleted first in case there is a geo inside geo
        geo_list = self.geo_list
        geo_list.reverse()
        for self.current_target in geo_list:
            pm.delete(self.current_target, ch=1)
            parent = pm.listRelatives(self.current_target, parent=True)
            pm.parent(self.current_target, w=True)
            pm.select(self.current_target)
            path = libFile.linux_path(libFile.join(self.export_dir, self.current_target + ".obj"))
            # Load the obj plugin
            cmds.file(path,
                      pr=1,
                      typ="OBJexport",
                      force=1,
                      options="groups=0;ptgroups=0;materials=0;smoothing=0;normals=0",
                      es=1)
            file_info[self.current_target] = path
            logger.info("Exporting\n%s" % file_info[self.current_target])
            if not self.new_scene and self.cleansing_mode:
                pm.delete(self.current_target)
                pm.refresh()
            else:
                pm.parent(self.current_target, parent)

            self.update_progress()

        # Write the geo file_info
        self.geo_file_info = file_info
def applyNodePositions(matrices, nodes):
    '''
    Applies the the given matrices to the given nodes in world space.

    Has some smarts for applying differing number of matrices to nodes.
    Ex:
        1 matrix, many nodes: All nodes are set to this matrix
        3 matrices, 2 nodes: First two matrices are applied.
        2 matrices, 3 nodes: IndexError is raised due to ambiguous case.
        3 matrices, 3 nodes: All three positions are applied.
    '''

    # Stop undo, so this doesn't get annoying for artist
    with internal.UndoChunk(), internal.MaintainSelection():

        # create temporary group outside of loop
        positionGroup = pm.group(n='mmo_applyPos_tmpGrp', em=1)

        # If passed a string instead of a list
        if isinstance(nodes, basestring):
            nodes = [nodes]

        # Make number of matrices match nodes
        if len(matrices) != len(nodes):

            # Much like GoodParenting, we allow 1 position to be applied to
            # multiple nodes. We also allow a partial application of matrices,
            # when there are more matrices passed than nodes.
            # The only case we can't handle, is when there are otherwise less
            # matrices than nodes.  It's ambiguous what to do if 2 matrices
            # were to be applied to 3 nodes.
            if len(matrices) == 1:
                matrices = matrices * len(nodes) # Copy list
            elif len(nodes) > len(matrices):
                raise IndexError('More nodes (%d) than saved matrices (%d)!' %
                    (len(nodes), len(matrices)))

        for matrix, node in zip(matrices, nodes):
            if not isinstance(node, pm.PyNode):
                node = pm.PyNode(node)
            # Don't constraint directly to selected, since it could be
            # something special or have stuff locked.  Create a duplicate of
            # selected group, and constrain that
            positionGroup.setMatrix(matrix, worldSpace=True)
            dummyGroup = duplicateGroup(node, 'mmo_applyPosDummy_tmpGrp')
            tempConst = pm.parentConstraint(positionGroup, dummyGroup)
            pm.refresh()

            # Copy attributes from the dummy group onto the real one.
            for attr in 'tx ty tz rx ry rz sx sy sz'.split():
                value = dummyGroup.getAttr(attr)
                try:
                    node.setAttr(attr, value)
                except RuntimeError:
                    _log.warning('Could not set value for %s.%s, skipping...',
                        node, attr)

            pm.delete(tempConst)
            pm.delete(dummyGroup)
        pm.delete(positionGroup)
예제 #19
0
파일: trileg.py 프로젝트: Mikfr83/crab
    def unlink_guide(self):
        """
        This should perform the operation to unlink the guide from the
        skeleton, leaving the skeleton completely free of any ties
        between it and the guide.

        This is run as part of the Rig.build process.

        We use this to ensure any locks we placed previously are unlocked
        before the control rig is built.

        :return: None
        """
        tags = [
            'SkeletonLowerLeg',
            'SkeletonAnkle',
            'SkeletonFoot',
            'SkeletonToe',
        ]

        for tag in tags:

            # -- Get the
            joint = self.find_first(tag)

            if joint:
                for attr in crab.utils.transform.transform_attrs():
                    joint.attr(attr).unlock()
                    joint.attr(attr).disconnect()
                print('unlcoked : %s' % joint)
            else:
                print('no dice : %s' % tag)
        pm.refresh()
        return True
예제 #20
0
 def import_hierarchy_geo(self):
     """Import all the obj objects"""
     file_info = self.geo_file_info
     for self.current_target in file_info.keys():
         cmds.file(file_info[self.current_target],
                   rpr="PKD_Temp",
                   i=1,
                   type="OBJ",
                   loadReferenceDepth="all",
                   ra=True,
                   mergeNamespacesOnClash=False,
                   options="mo=1")
         # Delete Existing geo if it exists
         if not self.cleansing_mode:
             if pm.objExists(self.current_target):
                 pm.delete(self.current_target)
         logger.info("Importing\n%s" % file_info[self.current_target])
         if self.cleansing_mode:
             os.remove(file_info[self.current_target])
         for top in pm.ls(assemblies=True, ud=True):
             if top.getShape():
                 if top.getShape().type() == "mesh" and top.name() == "PKD_Temp_Mesh":
                     top.rename(self.current_target)
                     pm.select(self.current_target)
                     mel.eval("polySetToFaceNormal")
                     mel.eval("polySoftEdge -a 180 -ch 1 %s" % self.current_target)
                     pm.delete(self.current_target, ch=1)
                     pm.refresh()
         self.update_progress()
예제 #21
0
def space_switch_bake(obj_list, start_time, end_time, matrix_dict):
    '''
    space_switch_bake(obj_list, start_time, end_time, matrix_dict)
    Key translate and rotate values of an object across a time range across states.  Store all world space
    matrix values in a list, run the method that will change the object state, then re-apply all world space
    values back across the time range.
    
    Args:
        obj (PyNode): Maya scene object to bake
        start_time (int): Start of the frame range for baking
        end_time (int): End of the frame range for baking
        matrix_dict (dict<list<matrix>>): List of world space matrix values for the provided object from start time to end time
    '''
    try:
        # Disable viewport refresh to speed up execution
        pm.refresh(su=True)
        bake_settings = v1_core.global_settings.GlobalSettings().get_category(
            v1_core.global_settings.BakeSettings)

        for i, frame in enumerate(xrange(start_time, end_time + 1)):
            pm.currentTime(frame)
            for obj in obj_list:
                if bake_settings.smart_bake:
                    if pm.keyframe(obj, q=True, t=frame):
                        pm.xform(obj, ws=True, matrix=matrix_dict[obj][i])
                        pm.setKeyframe(obj.t, t=frame)
                        pm.setKeyframe(obj.r, t=frame)
                else:
                    pm.xform(obj, ws=True, matrix=matrix_dict[obj][i])
                    pm.setKeyframe(obj.t, t=frame)
                    pm.setKeyframe(obj.r, t=frame)
    except Exception, e:
        raise e
예제 #22
0
 def reloadTextureList(cls, texList, *args, **kwargs):
     ''' reloads a list of texture nodes '''
     for item in texList:
         path = pm.getAttr(item + '.fileTextureName')
         if os.path.exists(path):
             pm.setAttr(item + '.fileTextureName', path)
     pm.refresh()
예제 #23
0
 def reloadTextures(cls, *args, **kwargs):
   ''' reloads all texture files in a scene '''
   sel = pm.ls(typ='file')
   for tex in sel:
     path = pm.getAttr(tex+'.fileTextureName')
     if os.path.exists(path):
       pm.setAttr(tex+'.fileTextureName',path)
   pm.refresh()
예제 #24
0
 def reloadTextures(cls, *args, **kwargs):
     ''' reloads all texture files in a scene '''
     sel = pm.ls(typ='file')
     for tex in sel:
         path = pm.getAttr(tex + '.fileTextureName')
         if os.path.exists(path):
             pm.setAttr(tex + '.fileTextureName', path)
     pm.refresh()
예제 #25
0
def gradient(*args):
    for i in xrange(0, 385, 40):
        pmc.button(interface['button'],
                   edit=True,
                   backgroundColor=(i / 1000., 0.385, i / 1000.))
        pmc.refresh()
        time.sleep(0.03)
    pmc.button(interface['button'], edit=True, noBackground=False)
예제 #26
0
 def reloadTexture(cls, texNode, *args, **kwargs):
     ''' reloads a single texture node '''
     path = pm.getAttr(texNode + '.fileTextureName')
     if os.path.exists(path):
         pm.setAttr(texNode + '.fileTextureName', path)
         lcUtility.Utility.lc_print('Reload Node: {0}, Path: {1}'.format(
             texNode, path))
     pm.refresh()
예제 #27
0
def jointChainOrient( objs=[] ): # wip
    '''
    update : 2015-04-29
    '''
    if objs:
        pm.selec(objs)
    objs = pm.ls(sl=True, o=True)
    if not objs:
        raise

    joints = pm.ls(sl=True, type='joint')
    if not joints:
        raise

    upMeshs = []
    if pm.filterExpand(sm=12):    
        upMeshs = [pm.PyNode(c) for c in pm.filterExpand(sm=12) ] # 업축으로 사용할 메쉬

    # 조인트 오리엔트 조정: 메쉬의 가장 가까운 점의 노말을 조인트의 up으로 설정
    if upMeshs:
        for jnt in joints:
            parentJnt = jnt.getParent()
            if parentJnt:
                # point에서 가장 가까운 Vertex의 Normal을 up으로 설정
                pos   = parentJnt.getTranslation( ws=True)
                vtx   = getClosestVertexOnMesh( upMeshs[0], pos )
                pos   = vtx.getPosition()
                norm  = vtx.getNormal()
                upPos = pos + norm * 1000000 # 노말 위치가 가까우면 방향이 틀어져 버림.. 그래서 큰 수를 곱함.

                upLoc = pm.spaceLocator(n='parentJnt_upLoc#')
                upLoc.t.set( upPos )

                jntOrient( [parentJnt, jnt, upLoc] )
                #pm.joint( parentJnt, edit=True, zso=True, oj='xyz', sao='yup' )
                pm.delete( upLoc )

    else:
        for jnt in joints:
            parentJnt = jnt.getParent()
            if parentJnt and parentJnt.type()=='joint':
                print jnt
                up = pm.spaceLocator()

                grandParent = parentJnt.getParent()
                if grandParent and grandParent.type()=='joint':
                    pm.delete( pm.parentConstraint( grandParent, up ) )                    
                else:
                    pm.delete( pm.parentConstraint( parentJnt, up ) )

                jntOrient( [parentJnt, jnt, up], worldUpType='objectrotation' )
                pm.refresh()
                pm.select(jnt)
                pm.delete(up)

    # 끝 조인트 오리엔트 조정
    if len(joints)>1:    
        pm.joint( joints[-1], edit=True, oj='none' )
예제 #28
0
def lcHideByTokenButton(vis, *args, **kwargs):
  ''' '''
  queryToken = pm.textField(prefix+'_textField_token',query=True,tx=True)
  meshAndXform = pm.ls(transforms=True) #list all transforms

  filtered = utility.filterByToken(meshAndXform, queryToken)
  utility.setTransformVisibility(filtered, vis)

  pm.refresh(force=True)
예제 #29
0
def lcHideByTokenButton(vis, *args, **kwargs):
    ''' '''
    queryToken = pm.textField(prefix + '_textField_token', query=True, tx=True)
    meshAndXform = pm.ls(transforms=True)  #list all transforms

    filtered = utility.filterByToken(meshAndXform, queryToken)
    utility.setTransformVisibility(filtered, vis)

    pm.refresh(force=True)
예제 #30
0
def lcBake_convert_lightmap(bakeSetListDropdown, cameraListDropdown, *args,
                            **kwargs):
    ''' '''
    global lct_cfg
    global prefix
    global defaultString
    global defaultPath

    sel = pm.ls(sl=True)

    numItems = bakeSetListDropdown.getNumberOfItems()
    if numItems > 0:
        currentBakeSet = bakeSetListDropdown.getValue()
        if currentBakeSet != defaultString:
            currentCamera = cameraListDropdown.getValue()
            outputDirectory = pm.textField(prefix + '_textField_texture_path',
                                           query=True,
                                           text=True)
            if os.path.exists(outputDirectory) or pm.PyNode(
                    currentBakeSet).nodeType() == 'vertexBakeSet':
                shadows = pm.checkBox(prefix + '_checkBox_shadows',
                                      query=True,
                                      value=True)

                if pm.control('bakeWindow', exists=True):
                    pm.deleteUI('bakeWindow')
                bakeWindow = pm.window('bakeWindow',
                                       t='Batch Bake',
                                       widthHeight=[100, 100],
                                       rtf=True,
                                       mnb=False,
                                       mxb=False,
                                       s=False)
                pm.columnLayout()
                pm.text(l='')
                pm.text(l='')
                pm.text(l='          Bake In Progress          ')
                pm.text(l='                  ......        ')
                pm.text(l='')
                pm.text(l='')
                bakeWindow.show()
                pm.refresh()

                if pm.PyNode(currentBakeSet).nodeType() == 'vertexBakeSet':
                    outputDirectory = 'None'

                convertString = lcBake.Bake.convertLightmap(
                    currentBakeSet, currentCamera, outputDirectory, shadows)

                sys.stdout.write('Convert Command: {0}'.format(convertString))

                pm.deleteUI('bakeWindow')

                pm.select(sel, replace=True)
            else:
                pm.warning('Path not found: {0}'.format(outputDirectory))
                pm.setFocus(prefix + '_textField_texture_path')
예제 #31
0
            def createWindow():
                """ try to get data from shotgun project fields
                    need to get context's project
                                context's shotgun instance
                """
                app = self.parent
                project = app.context.project
                sg = app.context.tank.shotgun
                # set filters and search fields for entity type "Project"
                filters=[["id", "is", project['id']],]
                fields=["sg_width", "sg_height"]
                result=sg.find_one("Project", filters, fields)
                # with result, set parameters accordingly or use default otherwise
                if result:
                    videoWidth = result.get("sg_width", DEFAULT_WIDTH)
                    videoHeight = result.get("sg_height", DEFAULT_HEIGHT)

                # Find first camera matching pattern and set as active camera
                # if not use default current active camera
                camera_name_pattern = app.get_setting( "camera_name_pattern", "persp" )
                cameraList = [c.name() for c in pm.ls(type="camera", r=True) if re.search( camera_name_pattern, c.name() )]
                if not "cam" in MODEL_EDITOR_PARAMS.keys() and cameraList:
                    MODEL_EDITOR_PARAMS["cam"] = cameraList[0]
                    
                # Give Viewport 2.0 renderer only for Maya 2015++
                # mayaVersionString = cmds.about(version=True)
                # mayaVersion = int(mayaVersionString[:4]) if len(mayaVersionString) >= 4 else 0
                # if mayaVersion >= 2015:
                #     params[ "rendererName" ] = "vp2Renderer"

                # Create window
                if pm.windowPref( PLAYBLAST_WINDOW, exists=True ):
                    pm.windowPref( PLAYBLAST_WINDOW, remove=True )
                window = pm.window( PLAYBLAST_WINDOW, titleBar=True, iconify=True,
                                      leftEdge = 100, topEdge = 100,
                                      width = videoWidth, height = videoHeight,
                                      sizeable = False)
                # Create editor area
                layout = pm.formLayout()
                editor = pm.modelEditor( **MODEL_EDITOR_PARAMS )
                pm.setFocus( editor )
                pm.formLayout( layout, edit=True,
                               attachForm = ( ( editor, "left", 0 ),
                                              ( editor, "top", 0 ),
                                              ( editor, "right", 0 ),
                                              ( editor, "bottom", 0 ) ) )
                # Show window
                pm.setFocus( editor )
                pm.showWindow( window )
                pm.refresh()
                try:
                    yield True
                except:
                    traceback.print_exc()
                finally:
                    pm.deleteUI(window)
    def create_window(self):
        """Create a custom window with related modelEditor, as well as running
        the pre- and post-window methods.

        Returns:
            bool: Success of the window, modelEditor, and pre- and post-
                window methods.
        """
        w_success = False

        # call various pre-window methods
        cam_check = self.set_camera()
        if cam_check:
            self.set_imageplanes_colorspace()
            self.set_vp2_globals()

            try:
                # create window (clean up first)
                self.destroy_window()

                window = pm.window(PLAYBLAST_WINDOW,
                                   titleBar=True,
                                   iconify=True,
                                   leftEdge=100,
                                   topEdge=100,
                                   width=DEFAULT_WIDTH,
                                   height=DEFAULT_HEIGHT,
                                   sizeable=False)

                # create window model editor
                layout = pm.formLayout()
                editor = pm.modelEditor(**MODEL_EDITOR_PARAMS)
                pm.setFocus(editor)

                pm.formLayout(layout,
                              edit=True,
                              attachForm=((editor, "left", 0), (editor, "top",
                                                                0),
                                          (editor, "right", 0), (editor,
                                                                 "bottom", 0)))

                # show window
                pm.setFocus(editor)
                pm.showWindow(window)
                pm.refresh()

                # call various post-window methods
                self.generate_all_uv_tile_previews()

                # success!
                w_success = True
            except Exception as e:
                m = '>> Failed to create playblast window > {}'.format(str(e))
                self.logger.info(m)

        return w_success
예제 #33
0
	def refresh(self, level= ''):
		"""
		level: 'Full', 'Palette', 'Description'
		"""
		if level:
			de = xgg.DescriptionEditor
			if de != None:
				de.refresh(level)
		else:
			pm.refresh()
예제 #34
0
def convert_joint_to_cluster(targetGeo, skipList=[]):
    """
    Convert a skin cluster to a cluster based setup on a target geometery
    @param targetGeo: the geometery which has the skin cluster
    @param skipList: any joints which should not processed such as a base joint
    @return A dictonary of cluster with the name of the joints as keys

    """
    # Convert to PyNode
    targetGeo = pm.PyNode(targetGeo)
    skin = libUtilities.get_target_defomer(targetGeo, "skinCluster")

    # Create the dictionary
    clusterInfo = {}
    # Progress Info
    pm.progressWindow(title='Converting Skin To Cluster', progress=0, status='Progress: 0%')
    totalJnts = len(skin.getInfluence()) - len(skipList)
    currentJnt = 0.0

    # Go through Each Joint
    for jnt in sorted(skin.getInfluence()):
        if jnt.name() in skipList:
            continue
        # Get the vertex affected and the weight
        vertZip, weightList = skin.getPointsAffectedByInfluence(jnt)
        if not vertZip:
            raise Exception("Current Joint Has No Vertices:%s" % jnt)
        pm.select(vertZip)

        # Iterate through selection and decompress vertic group  into individual index
        vertices = libUtilities.indexize_vertice_group(pm.selected())
        # Select Vertices
        libUtilities.select_vertices(targetGeo, vertices)
        # Make a cluster
        cltr, cTransform = pm.cluster(rel=1)
        jntPos = pm.xform(jnt, q=1, ws=1, rp=1)
        pm.setAttr(cTransform.scalePivot, jntPos)
        pm.setAttr(cTransform.rotatePivot, jntPos)

        # Set the weight
        for index, weight in zip(vertices, weightList):
            cltr.weightList[0].weights[index].set(weight)

        # Add to dictionary
        clusterInfo[jnt.name()] = {"cluster": cltr, "clusterHandle": cTransform}

        # Update Progress
        currentJnt = currentJnt + 1.0
        currentProgress = (currentJnt / totalJnts) * 100
        pm.progressWindow(edit=True, progress=currentProgress, status=('Progress: ' + str(int(currentProgress)) + '%'))
        pm.refresh()
        pyLog.info("Converted: " + jnt.name())

    pm.progressWindow(endProgress=1)
    return clusterInfo
예제 #35
0
 def drag_highlight(s, obj, face_id):
     """ highlight meshes """
     if obj:
         string_name = om.MFnDagNode(obj).fullPathName()
         node = pmc.PyNode(string_name)  # Convert to pymel again, boo!
         try:
             joint = s.cache_pref[node][face_id]
             influence = s.cache_inf[joint]
             colour.paint(influence, YELLOW)
             pmc.refresh()
         except KeyError as e:
             print "Missing node", e
예제 #36
0
def updateHighlight(faces):
    '''
    faces - list of faces to add to shadingEngine
    if None, just hide the mesh
    
    TODO: implement different types of highlights, for 
    ik, fk, tweaks, etc
    '''
    # mesh = pm.PyNode('CT_mesh_hilight_shd')
    sg = pm.PyNode('lambert3SG')

    pm.sets(sg, add=faces)
    pm.refresh()
예제 #37
0
 def dragging(s, mesh, ID):
     """ dragging mesh """
     try:
         if mesh: # Are we still dragging on the mesh?
             joint = s.cache_weights[mesh][ID]
             if joint != s.drag_joint:
                 s.drag_joint = joint
                 canvas = s.cache_influence[joint]
                 s.canvas.paint(s.cache_all) # Clear canvas
                 s.canvas.paint(canvas, GREEN)
                 pmc.refresh() # Update display
     except KeyError:
         print "Joint missing from cache."
예제 #38
0
def updateHighlight(faces):
    '''
    faces - list of faces to add to shadingEngine
    if None, just hide the mesh
    
    TODO: implement different types of highlights, for 
    ik, fk, tweaks, etc
    '''
    # mesh = pm.PyNode('CT_mesh_hilight_shd')
    sg = pm.PyNode('lambert3SG')
    
    pm.sets(sg, add=faces)
    pm.refresh()
예제 #39
0
    def doIt(self, args):

        result = pm.promptDialog(title='Kraken: Build Biped',
                                 message='Rig Name',
                                 button=['OK', 'Cancel'],
                                 defaultButton='OK',
                                 cancelButton='Cancel',
                                 text='Biped')

        if result == 'OK':
            guideName = pm.promptDialog(query=True, text=True)
            guideName.replace(' ', '')
            guideName += '_guide'

            guideRig = BipedGuideRig(guideName)

            builder = plugins.getBuilder()

            OpenMaya.MGlobal.displayInfo('Kraken: Building Guide Rig: ' +
                                         guideName)

            try:
                main_window = pm.ui.Window(pm.MelGlobals.get('gMainWindow'))
                main_win_width = pm.window(main_window, query=True, width=True)

                buildMsgWin = pm.window("KrakenBuildBipedWin",
                                        title="Kraken: Build Biped",
                                        width=200,
                                        height=100,
                                        sizeable=False,
                                        titleBar=False,
                                        leftEdge=(main_win_width / 2) - 100)

                buildMsglayout = pm.verticalLayout(spacing=10)
                buildMsgText = pm.text('Kraken: Building Biped')
                buildMsglayout.redistribute()
                buildMsgWin.show()

                pm.refresh()

                builtRig = builder.build(guideRig)

                return builtRig

            finally:
                if pm.window("KrakenBuildBipedWin", exists=True) is True:
                    pm.deleteUI(buildMsgWin)

        else:
            OpenMaya.MGlobal.displayWarning(
                'Kraken: Build Guide Rig Cancelled!')
예제 #40
0
def loop_to_joints(s=0.025):
    """Convert a mesh loop edge selection to a nurbs curve that has
    joints (w/ tweak controls) at each vertex. Opens dialog for naming."""
    edges = pmc.selected(flatten=True)
    cage = edges[0].node()

    try:
        n = make_dialog("Name of this curve/region?") + "{}"
    except TypeError:
        pmc.warning("Aborted.")
        return

    c = pmc.PyNode(pmc.polyToCurve(n=n.format("_rider"))[0])
    verts = set([v for e in edges for v in e.connectedVertices()])
    grp = pmc.group(em=True, n=n.format("_grp"))
    c.setParent(grp)
    jn = ""

    for i, v in enumerate(verts):
        pmc.select(c)
        pmc.selectMode(component=True)
        pmc.select(c.u[i])
        pmc.refresh()
        jn = make_dialog("Name of this joint?", jn)
        poci = pmc.nt.PointOnCurveInfo(n=n.format(jn + "_poci"))
        c.ws >> poci.inputCurve
        poci.parameter.set(i)
        ctrl_grp = pmc.group(em=True, n=n.format(jn + "_offset"))
        ctrl_grp.setParent(grp)
        ctrl = pmc.sphere(r=s, s=1, nsp=1, ch=0,
                          n=n.format(jn + "_tweakCtrl"))[0]
        ctrl.setParent(ctrl_grp)
        j = pmc.joint(n=n.format(jn + "_rig"))
        j.setParent(ctrl)
        j.hide()

        poci.position >> ctrl_grp.translate
        nCon = pmc.normalConstraint(cage, ctrl_grp)
        poci.nt >> nCon.worldUpVector

        # remove graph cluster
        nCon.crp.disconnect()
        nCon.crt.disconnect()
        nCon.cro.disconnect()
        nCon.cpim.disconnect()
        nCon.ct.disconnect()

        poci.position >> nCon.constraintTranslate
        grp.wim >> nCon.cpim

    pmc.selectMode(object=True)
예제 #41
0
    def testBuild(self, **kwargs):

        jointSystem = kwargs.get("jointSystem")
        buildProxy = kwargs.get("buildProxy", True)
        buildMaster = kwargs.get("buildMaster", True)

        if not jointSystem:
            # Build the help joints
            jointSystem = joints.JointSystem(side=self.side, part="%sJoints" % self.part)
            self.jointSystem = jointSystem
            pm.refresh()

            # Build the joints
            testJoints = None
            currentClass = self.__class__
            originalClass = self.__class__
            while not testJoints:
                # Try to build for current class
                try:
                    testJoints = utils.createTestJoint(currentClass.__name__)
                except:
                    # look in the parent class
                    if currentClass == object:
                        print originalClass.__name__
                        testJoints = utils.createTestJoint(originalClass.__name__)
                    else:
                        currentClass = currentClass.__bases__[0]

            # Setup the joint system
            self.jointSystem.joints = libUtilities.stringList(testJoints)
            self.jointSystem.convertJointsToMetaJoints()
            self.jointSystem.setRotateOrder(self.rotateOrder)
        else:
            self.jointSystem = jointSystem
            # Build the Part
        self.rotateOrder = self.jointSystem.rotateOrder
        self.build()

        if buildProxy:
            # build proxy
            self.buildProxy()

        if buildMaster:
            # Build Master Control
            pm.select(cl=1)
            masterControl = self.createCtrlObj("master", shape="Square", createXtra=False)
            masterControl.prnt.pynode.setParent(world=True)

            self.addConstraint(masterControl.pynode)
            self.addConstraint(masterControl.pynode, "scale")
예제 #42
0
def bakeAnimation(nodes):
    """
    Bakes animation on the given nodes for the current timeline.
    
    Args:
        nodes(list): A list of nodes. 
    """
    try:
        pmc.refresh(su=True)
        start = pmc.playbackOptions(minTime=True, q=True)
        end = pmc.playbackOptions(maxTime=True, q=True)
        pmc.bakeResults(nodes, at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'], t=(start, end), simulation=True)
    finally:
        pmc.refresh(su=False)
예제 #43
0
def build():
    '''
    '''
    mesh = nt.Mesh(u'CT_hat_simplegeoShape')   
    placementGrp = nt.Transform(u'CT_placement_grp')
    
    #---------------------------------------------------------------------- bind
    if 'bind' in data.build_actions:
        bindGrp = face.createBndsFromPlacement(placementGrp)
        pm.refresh()
    else:
        bindGrp = nt.Transform(u'CT_bnd_grp')
    
    #--------------------------------------------------------- sec motion system
    if 'sec_motion_system' in data.build_actions:
        face.buildSecondaryControlSystem(placementGrp, bindGrp, mesh)
        pm.refresh()
     
    #------------------------------------------------------------ pri ctl system first
    if 'primary_ctl_system_first' in data.build_actions:
        # run a simple first pass
        # which can be used to block out mappings
        bndsForPriCtls = data.all_bnds_for_priCtls
        priCtl.setupPriCtlFirstPass(bindGrp, bndsForPriCtls)
        priCtl.driveAttachedPriCtlsRun(bindGrp)
            
    #------------------------------------------------------------ pri ctl system second
    if 'primary_ctl_system_second' in data.build_actions:
        if data.priCtlMappings:
            # if priCtlMappings is set up, use the data
            priCtlMappings = data.priCtlMappings
            priCtl.setupPriCtlSecondPass(priCtlMappings)
            priCtl.driveAttachedPriCtlsRun(bindGrp)
            pm.refresh()
        else:
            pm.warning('no data for pri ctl system')
            
    #-------------------------------------------------------------- load weights
    if 'load_weights' in data.build_actions:
        priCtlWeights = data.priCtlWeights
        priCtl.setPriCtlSecondPassWeights(priCtlWeights)
        pm.refresh()
            
    #--------------------------------------------------------------------- clean
    if 'clean' in data.build_actions:
        print 'clean'
        face.cleanFaceRig()
        pm.select(cl=True)
        pm.refresh()
예제 #44
0
    def doIt(self, args):

        result = pm.promptDialog(title='Kraken: Build Biped',
                                 message='Rig Name',
                                 button=['OK', 'Cancel'],
                                 defaultButton='OK',
                                 cancelButton='Cancel',
                                 text='Biped')

        if result == 'OK':
            guideName = pm.promptDialog(query=True, text=True)
            guideName.replace(' ', '')
            guideName += '_guide'

            guideRig = BipedGuideRig(guideName)

            builder = plugins.getBuilder()

            OpenMaya.MGlobal.displayInfo('Kraken: Building Guide Rig: ' + guideName)

            try:
                main_window = pm.ui.Window(pm.MelGlobals.get('gMainWindow'))
                main_win_width = pm.window(main_window, query=True, width=True)

                buildMsgWin = pm.window("KrakenBuildBipedWin",
                                        title="Kraken: Build Biped",
                                        width=200,
                                        height=100,
                                        sizeable=False,
                                        titleBar=False,
                                        leftEdge=(main_win_width / 2) - 100)

                buildMsglayout = pm.verticalLayout(spacing=10)
                buildMsgText = pm.text('Kraken: Building Biped')
                buildMsglayout.redistribute()
                buildMsgWin.show()

                pm.refresh()

                builtRig = builder.build(guideRig)

                return builtRig

            finally:
                if pm.window("KrakenBuildBipedWin", exists=True) is True:
                    pm.deleteUI(buildMsgWin)

        else:
            OpenMaya.MGlobal.displayWarning('Kraken: Build Guide Rig Cancelled!')
예제 #45
0
def build():
    '''
    '''
    mesh = nt.Mesh(u'CT_hat_simplegeoShape')
    placementGrp = nt.Transform(u'CT_placement_grp')

    #---------------------------------------------------------------------- bind
    if 'bind' in data.build_actions:
        bindGrp = face.createBndsFromPlacement(placementGrp)
        pm.refresh()
    else:
        bindGrp = nt.Transform(u'CT_bnd_grp')

    #--------------------------------------------------------- sec motion system
    if 'sec_motion_system' in data.build_actions:
        face.buildSecondaryControlSystem(placementGrp, bindGrp, mesh)
        pm.refresh()

    #------------------------------------------------------------ pri ctl system first
    if 'primary_ctl_system_first' in data.build_actions:
        # run a simple first pass
        # which can be used to block out mappings
        bndsForPriCtls = data.all_bnds_for_priCtls
        priCtl.setupPriCtlFirstPass(bindGrp, bndsForPriCtls)
        priCtl.driveAttachedPriCtlsRun(bindGrp)

    #------------------------------------------------------------ pri ctl system second
    if 'primary_ctl_system_second' in data.build_actions:
        if data.priCtlMappings:
            # if priCtlMappings is set up, use the data
            priCtlMappings = data.priCtlMappings
            priCtl.setupPriCtlSecondPass(priCtlMappings)
            priCtl.driveAttachedPriCtlsRun(bindGrp)
            pm.refresh()
        else:
            pm.warning('no data for pri ctl system')

    #-------------------------------------------------------------- load weights
    if 'load_weights' in data.build_actions:
        priCtlWeights = data.priCtlWeights
        priCtl.setPriCtlSecondPassWeights(priCtlWeights)
        pm.refresh()

    #--------------------------------------------------------------------- clean
    if 'clean' in data.build_actions:
        print 'clean'
        face.cleanFaceRig()
        pm.select(cl=True)
        pm.refresh()
예제 #46
0
def ikFkRange(control, start=None, end=None):
    action = activateIk if control.fossilCtrlType.get() in ['ik'
                                                            ] else activateFk

    otherObj = control.getOtherMotionType()

    drivePlug = controllerShape.getSwitcherPlug(control)
    if drivePlug:
        driver = lambda: setAttr(drivePlug, 1)  # noqa E731
    else:
        if control.fossilCtrlType.get() in ['ik']:
            switch = _getSwitchPlug(otherObj)[0].node()
            plug = switch.input1D.listConnections(p=True)[0]
            driver = lambda: plug.set(1)  # noqa E731
        else:
            switch = _getSwitchPlug(control)[0].node()
            plug = switch.input1D.listConnections(p=True)[0]
            driver = lambda: plug.set(1)  # noqa E731

    controls = [ctrl
                for name, ctrl in otherObj.subControl.items()] + [otherObj]
    times = set()

    for c in controls:
        times.update(keyframe(c, q=True, tc=True))

    finalRange = []
    for t in sorted(times):
        if start is not None and t < start:
            continue
        if end is not None and t > end:
            continue

        finalRange.append(t)

    targetControls = [ctrl for name, ctrl in control.subControl.items()
                      ] + [control]

    with core.ui.NoUpdate():
        for t in finalRange:
            currentTime(t)
            driver()
            action(control)
            refresh()
            setKeyframe(targetControls, shape=False)

            if drivePlug:
                setKeyframe(drivePlug)
예제 #47
0
def parent_shape(src, target, delete_src=True, delete_oldShape=True):
    '''parent shape from source to target'''
    #pm.parent(src, world=True)
    print src, target
    pm.makeIdentity(src, apply=True)
    pm.delete(src.listRelatives(type='transform'))
    pm.refresh()
    if delete_oldShape:
        pm.delete(get_shape(target), shape=True)
    if delete_src:
        pm.parent(src.getShape(), target, r=True, s=True)
        pm.delete(src)
    else:
        temp = src.duplicate()[0]
        pm.parent(temp.getShape(), target, r=True, s=True)
        pm.delete(temp)
예제 #48
0
def lcBake_convert_lightmap(bakeSetListDropdown, cameraListDropdown, *args,
                            **kwargs):
    ''' '''
    numItems = bakeSetListDropdown.getNumberOfItems()
    if numItems > 0:
        currentBakeSet = bakeSetListDropdown.getValue()
        if currentBakeSet:
            currentCamera = cameraListDropdown.getValue()
            outputDirectory = pm.textField(prefix + '_textField_texture_path',
                                           query=True,
                                           text=True)
            if os.path.exists(outputDirectory):
                shadows = pm.checkBox(prefix + '_checkBox_shadows',
                                      query=True,
                                      value=True)

                if pm.control('bakeWindow', exists=True):
                    pm.deleteUI('bakeWindow')
                bakeWindow = pm.window('bakeWindow',
                                       t='Batch Bake',
                                       widthHeight=[100, 100],
                                       rtf=True,
                                       mnb=False,
                                       mxb=False,
                                       s=False)
                pm.columnLayout()
                pm.text(l='')
                pm.text(l='')
                pm.text(l='          Bake In Progress          ')
                pm.text(l='                  ......        ')
                pm.text(l='')
                pm.text(l='')
                bakeWindow.show()
                pm.refresh()
                #pm.pause(seconds=10)

                convertString = bake.convertLightmap(currentBakeSet,
                                                     currentCamera,
                                                     outputDirectory, shadows)

                print('Convert Command: {0}'.format(convertString))

                pm.deleteUI('bakeWindow')

                pm.select(clear=True)
            else:
                pm.warning('Path not found: {0}'.format(outputDirectory))
예제 #49
0
 def main(self,imagePath):
     # get camera
     cam = get_current_cam()
     set_attr_for_pb(cam)
     imageName = '%s/%s' % (imagePath,cam.name())
     # grab image
     # get current time
     min_time = int(pm.playbackOptions( q=True,minTime=True )) 
     max_time = int(pm.playbackOptions( q=True,maxTime=True )) + 1
     for i in range(min_time,max_time):
         pm.currentTime(i,e=1,update=1)
         pm.refresh(f=1)
         #panel = pm.paneLayout('viewPanes', q=True, pane1=True)
         #pm.isolateSelect(panel,state=1)
         #pm.isolateSelect(panel,state=0)
         #self.grab_view( '%s.%s.jpg' % (imageName,i) )
         self.grab_view( '%s.%s.jpg' % (imageName,i) )
예제 #50
0
 def main(self, imagePath):
     # get camera
     cam = get_current_cam()
     set_attr_for_pb(cam)
     imageName = '%s/%s' % (imagePath, cam.name())
     # grab image
     # get current time
     min_time = int(pm.playbackOptions(q=True, minTime=True))
     max_time = int(pm.playbackOptions(q=True, maxTime=True)) + 1
     for i in range(min_time, max_time):
         pm.currentTime(i, e=1, update=1)
         pm.refresh(f=1)
         #panel = pm.paneLayout('viewPanes', q=True, pane1=True)
         #pm.isolateSelect(panel,state=1)
         #pm.isolateSelect(panel,state=0)
         #self.grab_view( '%s.%s.jpg' % (imageName,i) )
         self.grab_view('%s.%s.jpg' % (imageName, i))
예제 #51
0
    def update_main_game_loop(self):
        """The main game loop.

        1. Get the current delta time
        2. Update the key map
        3. Update all registered game objects
        """
        delta_time = self.delta_time()

        if delta_time >= 1.0 / self.target_fps:
            self.update_keys(delta_time)
            for game_object in [g for g in self.game_objects if g.enabled]:
                game_object.update(delta_time)
            # end for
            self.time_node.setAttr('unwarpedTime', self.time_node.getAttr('unwarpedTime') + delta_time * 24)
            self.time_node.setAttr('outTime', self.time_node.getAttr('outTime') + delta_time * 24)
            pm.refresh(f=True)
        else:
            pm.refresh(f=True)
예제 #52
0
파일: core.py 프로젝트: etic/mayabox
	def exportNode(self, node, tag, moveToOrigin=True):
		pm.mel.eval('print "Exporting {0}"'.format(node))
		pm.refresh()
		# zero node transforms and select node
		if moveToOrigin:
			wm = getWorldMatrix(node)
			setWorldMatrix(node, pm.dt.TransformationMatrix(), scale=False)
		sel = pm.selected()
		pm.select(node)
		exportFuncs = {
			_UDK_TAG : self._exportNodeUDK,
			_ZBRUSH_TAG : self._exportNodeZbrush,
			_XNORMAL_TAG : self._exportNodeXnormal,
		}
		exportFuncs[tag](node)
		# move node back to original position and reset selection
		if moveToOrigin:
			setWorldMatrix(node, wm, scale=False)
		pm.select(sel)
예제 #53
0
    def mouseReleaseEvent(self, event):
        """Start the Game and run the game loop.

        Allows to receive user input while running a game loop.
        """
        if GameEngine().running:
            self.parent().stop()
            return
        # end if
        self.parent().parent()._on_start()
        self.parent().parent().on_start()
        game_engine = GameEngine()
        game_engine.start()
        pm.refresh(f=True)
        while game_engine.running:
            if not game_engine.paused:
                game_engine.update_main_game_loop()
            # end if
        # end while
        return QtGui.QPushButton.mouseReleaseEvent(self, event)
예제 #54
0
def switch(switch = 0, value = 32):
    files = pm.ls(type = "file")
    
    attrName = "resolution"
    
    for f in files:
        #switch = 0, 为贴图32位显示; switch = 1,  为默认高精度显示;
        if switch :
            if f.hasAttr(attrName):
                f.resolution.delete()
            else :
                pass
        else :
            if f.hasAttr(attrName):
                f.resolution.set(value)
            else :
                pm.addAttr(f, ln = "resolution",at ="long", dv=value)
        pm.refreshEditorTemplates()
        pm.refresh()
    pm.confirmDialog(title='Switch', message='转换完成', button = ['OK'])
예제 #55
0
파일: view.py 프로젝트: bohdon/viewGui
 def buildBody(self):
     self._iconSize = self.gui.iconSize
     self.minSize = 128
     self.maxSize = 512
     self.tempFileName = 'mayaIcon{0}.png'
     self.gui.window.setToolbox(True)
     self.camera = self.newCamera()
     with pm.formLayout() as form:
         with pm.columnLayout():
             kw = dict(w=128, h=128)
             with pm.frameLayout(lv=False, bv=False, **kw) as self.editorFrame:
                 self.panel = pm.modelPanel(cam=self.camera, mbv=False, l='Icon Capture View')
                 self.setupModelEditor(self.panel.getModelEditor())
                 bar = self.panel.getBarLayout()
                 pm.layout(bar, e=True, m=False)
         with pm.formLayout() as form2:
             self.buildFooter()
             utils.layoutForm(form2, 1)
         utils.layoutForm(form, (0, 1), vertical=True)
     self.updateEditorFrame()
     pm.refresh()
def getNodePositions(nodes):
    '''
    Returns a list of world matrices of the given nodes.


    Returned matrices are always scaled to (1, 1, 1). Return type is
    [pm.dt.Matrix, ..]
    '''

    # It would be really REALLY easy to query world matrices directly
    # from Maya, but we'll be EXTRA careful, and do a bunch of extra
    # work to use parent constraints first, because in my experience
    # this works more reliably in rare edge cases.
    positions = []

    # Stop undo, so this doesn't get annoying for artist
    with internal.UndoChunk(), internal.MaintainSelection():

        # Create tempgroup and parent constrain it to object to get position
        # Maya likes this approach better
        tempGroup = pm.group(n='mmo_savePos_tmpGrp', em=1)

        # If passed a string instead of a list
        if isinstance(nodes, basestring):
            nodes = [nodes]

        # Get position with parent constraints
        for node in nodes:
            if not isinstance(node, pm.PyNode):
                node = pm.PyNode(node)
            tempConst = pm.parentConstraint(node, tempGroup)
            pm.refresh()
            positions.append(tempGroup.getMatrix(worldSpace=1))
            pm.delete(tempConst)

        # Delete temp group
        pm.delete(tempGroup)

    return positions
예제 #57
0
def adapt_to_orig_shape(source, target):
    """
    :param source: source shape to transfer
    :param target: target to transfer to
     This is based out of Renaud's code on shape to orig when building and unbuilding with omtk to preserve shape info.
    """

    def get_transformGeometry(shape):
        return next((hist for hist in shape.listHistory()
                     if isinstance(hist, pymel.nodetypes.TransformGeometry)), None)

    # Resolve orig shape
    shape_orig = get_orig_shape(target)

    # Resolve compensation matrix
    util_transform_geometry = get_transformGeometry(target)
    if not util_transform_geometry:
        target.warning("Skipping {}. Cannot find transformGeometry.".format(target))
        return
    attr_compensation_tm = next(iter(util_transform_geometry.transform.inputs(plugs=True)), None)

    if not attr_compensation_tm:
        target.warning("Skipping {}. Cannot find compensation matrix.".format(target))
        return

    tmp_transform_geometry = libRigging.create_utility_node(
        'transformGeometry',
        inputGeometry=source.local,
        transform=attr_compensation_tm,
        invertTransform=True
    )

    # source.getParent().setParent(grp_offset) JG modification source should already be in place
    pymel.connectAttr(tmp_transform_geometry.outputGeometry, shape_orig.create)

    # Cleanup
    pymel.refresh(force=True)  # but why do I have to refresh^!
    pymel.disconnectAttr(shape_orig.create)
    pymel.delete(tmp_transform_geometry)
예제 #58
0
def convert_joint_to_cluster(targetGeo, skipList=None, info=False):
    """
    Convert a skin cluster to a cluster based setup on a target geometery
    @param info: Whether to just query the data for in case we are building it later
    @param skipList: The joints which need to be skipped
    @param targetGeo: (string/pynode) The geometry which has the skin cluster
    @param skipList: (list) Any joints which should not processed such as a base joint
    @return A dictionary of cluster with the name of the joints as keys

    """
    if skipList is None:
        skipList = []
        # Convert to PyNode
    targetGeo = libUtilities.force_pynode(targetGeo)
    skin_name = libUtilities.get_target_defomer(targetGeo, "skinCluster")
    skin = libUtilities.force_pynode(skin_name)
    # Create the dictionary
    clusterInfo = {}
    # Progress Info
    pm.progressWindow(title='Converting Skin To Cluster', progress=0, status='Progress: 0%')
    totalJnts = len(skin.getInfluence()) - len(skipList)
    currentJnt = 0.0

    # Go through Each Joint
    for jnt in sorted(skin.getInfluence()):
        if jnt.name() in skipList:
            continue
        # Get the vertex affected and the weight
        vertZip, weightList = skin.getPointsAffectedByInfluence(jnt)
        if not vertZip:
            raise RuntimeError("Current Joint Has No Vertices:%s" % jnt)
        pm.select(vertZip)

        # Iterate through selection and decompress vertix group into individual index
        vertices = libUtilities.indexize_vertice_group(pm.selected())

        joint_position = pm.xform(jnt, q=1, ws=1, rp=1)
        # Select Vertices
        if info:
            clusterInfo[jnt.name()] = {"vertices": libUtilities.stringList(vertices),
                                       "weight": weightList,
                                       "position": joint_position}
        else:
            libUtilities.select_vertices(targetGeo, vertices)
            # Make a cluster
            cluster_info = weighted_cluster(targetGeo, vertices, weightList, joint_position)

            # Add to dictionary
            clusterInfo[jnt.name()] = cluster_info

        # Update Progress
        currentJnt += 1.0
        currentProgress = (currentJnt / totalJnts) * 100
        pm.progressWindow(edit=True, progress=currentProgress, status=('Progress: ' + str(int(currentProgress)) + '%'))
        pm.refresh()
        if info:
            logger.info("Info gathered: " + jnt.name())
        else:
            logger.info("Converted: " + jnt.name())

    pm.progressWindow(endProgress=1)
    return clusterInfo
    def process(self, instance):

        def temp_dir():
            import tempfile
            extract_dir = tempfile.mkdtemp()
            return extract_dir



        self.log.info("Extracting full capture..")
        #ftrackData = context.data.get('ftrackData')

        if instance.context.data.get('ftrackData'):
            if instance.context.data['ftrackData']['Project']['code'] == 'hbt':
                self.log.info("Switching texures to LOW")
                import hbt_switch_tex as hbtSw
                reload(hbtSw)

                nhbtData=hbtSw.switchTexture()

                nhbtData.option = 1
                nhbtData.highest = False
                nhbtData.limit = 1600
                nhbtData.validatorCheck()
                nhbtData.fast = False

                nhbtData.all = True
                nhbtData.forceReload = True
                nhbtData.switch()

                pm.refresh(f=True)


        components = instance.data['ftrackComponents'].copy()
        self.log.debug('Components: {}'.format(components))

        camera = instance[0]

        if 'persp' in camera:
            self.log.info("If you want movie review, create a camera with \
                          '_cam' suffix")
            return


        ftrack_data = instance.context.data['ftrackData']

        project_code = ftrack_data['Project']['code']
        task_type = ftrack_data['Task']['type']

        if 'Asset_Build' in ftrack_data:
            asset = ftrack_data['Asset_Build']['name']
        elif 'Shot' in ftrack_data:
            asset = ftrack_data['Shot']['name']


        ftrackStrings = fStrings.annotationData()
        nData = ftrackStrings.niceData
        nData['version'] = instance.context.data('version')

        fFrame = int(float(nData['oFStart']))
        eFrame = int(float(nData['oFEnd']))
        fHandle = int(float(nData['handle']))
        soundOfst = 0 #fFrame - fHandle - fFrame
        nData['frame'] = [(str("{0:05d}".format(f))) for f in range(fFrame - fHandle, eFrame + fHandle + 1)]



        # load Preset
        studio_repos = os.path.abspath(os.environ.get('studio_repos'))
        shot_preset_path = os.path.join(studio_repos, 'maya',
                                    'capture_gui_presets',
                                   (project_code + '_' + task_type + '_' + asset + '.json'))

        task_preset_path = os.path.join(studio_repos, 'maya',
                                    'capture_gui_presets',
                                   (project_code + '_' + task_type + '.json'))

        project_preset_path = os.path.join(studio_repos, 'maya',
                                   'capture_gui_presets',
                                   (project_code + '.json'))

        default_preset_path = os.path.join(studio_repos, 'maya',
                                   'capture_gui_presets',
                                   'default.json')

        # my_file = Path("/path/to/file")
        if os.path.isfile(shot_preset_path):
            preset_to_use = shot_preset_path
        elif os.path.isfile(task_preset_path):
            preset_to_use = task_preset_path
        elif os.path.isfile(project_preset_path):
            preset_to_use = project_preset_path
        else:
            preset_to_use = default_preset_path

        preset = pyblish_utils.load_capture_preset(preset_to_use)
        self.log.info('using viewport preset: {}'.format(preset_to_use))


        #preset["off_screen"] =  False

        preset['camera'] = camera
        preset['format'] = "image"
        preset['compression'] = "jpg"
        preset['quality'] = 95
        #preset['compression'] = "H.264"
        preset['camera_options'] = {
            "displayGateMask": False,
            "displayResolution": False,
            "displayFilmGate": False,
            "displayFieldChart": False,
            "displaySafeAction": False,
            "displaySafeTitle": False,
            "displayFilmPivot": False,
            "displayFilmOrigin": False,
            "overscan": 1.0,
            "depthOfField": cmds.getAttr("{0}.depthOfField".format(camera))
        }

        dir_path = temp_dir()

        # Ensure name of camera is valid
        sourcePath = os.path.normpath(instance.context.data('currentFile'))
        path, extension = os.path.splitext(sourcePath)
        image_folder, filename = os.path.split(path)
        output_images = os.path.join(dir_path, filename)

        self.log.info("Outputting images to %s" % output_images)


        preset['filename'] = output_images
        preset['overwrite'] = True


        preset['start_frame'] = fFrame - fHandle
        preset['end_frame'] = eFrame + fHandle

        pm.refresh(f=True)


        refreshFrameInt = fFrame - fHandle
        pm.currentTime( refreshFrameInt - 1, edit=True )
        pm.currentTime( refreshFrameInt, edit=True )

        with maintained_time():
            playblast = capture_gui.lib.capture_scene(preset)


        self.log.info("Calculating HUD data overlay")

        movieFullPth = output_images + ".mov"
        #wildCardMoviePth = output_images + ".*"
        fls = [os.path.join(dir_path, f).replace("\\","/") for f in os.listdir( dir_path ) if f.endswith(preset['compression'])]
        #self.log.info(" these  %s" % fls[0])



        soundFile = mu.giveMePublishedAudio()
        self.log.info("SOUND offset  %s" % str(soundOfst))
        self.log.info("SOUND source video to %s" % str(soundFile))
        ann = dHUD.draftAnnotate()
        if soundFile:
            ann.addAnotation(seqFls = fls, outputMoviePth = movieFullPth, annotateDataArr = nData, soundFile = soundFile, soundOffset = soundOfst)
        else:
            ann.addAnotation(seqFls = fls, outputMoviePth = movieFullPth, annotateDataArr = nData)


        for f in fls:
            os.remove(f)

        playblast = (ann.expPth).replace("\\","/")
        instance.data["handleOutputPath_qt"] = movieFullPth
        self.log.info("Outputting full video to %s" % movieFullPth)