Пример #1
0
 def buildUI(self):
     
     # Make sure there are no duplicated UI
     if pc.window(self.windowName, exists=True):
         pc.deleteUI(self.windowName)
     if pc.dockControl(self.windowName+'_dock', exists=True):
         pc.deleteUI(self.windowName+'_dock')
     
     # Dock window
     self.uiWidgets['window'] = pc.window(self.windowName, title=self.windowName, h=self.windowHeight, w=self.windowWidth, mnb=False, mxb=False, sizeable=False)
     
     # Layout and dock
     self.uiWidgets['layout'] = pc.columnLayout(p=self.uiWidgets['window'])
     pc.dockControl(self.windowName+'_dock', label=self.windowName, area='right', content=self.uiWidgets['window'])
     
     #### Tabs and buttons creation
     # Categories list
     categories = {}
     
     # Check for file that has to be ignored
     ignoreFile = open(pc.internalVar(upd=True)+'scripts/'+self.scanFolder+'/ignore.txt')
     ignoredFiles = []
     for line in ignoreFile:
         ignoredFiles.append(line.replace('\n',''))
     
     # Check for existing *.py files in the script/self.scanFolder folder
     for pyscript in os.listdir(pc.internalVar(upd=True)+'scripts/'+self.scanFolder):
         if fnmatch.fnmatch(pyscript, '*.py') and pyscript not in ignoredFiles:
             # Get the category for later use
             category = pyscript.partition('_')[0]
             # If category is not empty
             if category != '':
                 if category not in categories.keys():
                     categories[category] = []
                 # Append the icon path associated to the script
                 print "Adding script '%s' to shelf." % pyscript
                 categories[category].append(pyscript.partition('.')[0]+'.png')
                 
     print categories
     
     for category in categories.keys():
         self.uiWidgets[category+'_frameLayout'] = pc.frameLayout(label=category.capitalize(), borderStyle='etchedIn', cll=True, w=self.windowWidth, parent=self.uiWidgets['layout'])
         
         self.uiWidgets[category+'_rcLayout']= pc.rowColumnLayout(nc=3, p=self.uiWidgets[category+'_frameLayout'])
         
         for icon in categories[category]:
             iconPath = pc.internalVar(upd=True)+'icons/'+self.scanFolder+'/'+icon
             # If icon exists, we use it
             if os.path.exists(iconPath):
                 pc.iconTextButton(w=35, h=35, i1=iconPath,c=partial(self.loadScript, icon.partition('.')[0]))
             else:
                 pc.iconTextButton(iol=icon.partition('.')[0].partition('_')[2], w=35, h=35, i1=pc.internalVar(upd=True)+'icons/'+self.scanFolder+'/missing.png',c=partial(self.loadScript, icon.partition('.')[0]))
Пример #2
0
def UI():
	# find ui files
	ehm_uiPath = pm.internalVar( uad=True ) + 'scripts/ehm_tools/ui/'
	
	# delete window if exists
	if pm.window( 'offsetBlends.ui', q=True,  exists=True ):
		pm.deleteUI( 'offsetBlends.ui' )
	
	# load ui
	uiFile = pm.loadUI( uiFile = ehm_uiPath + 'offsetBlends.ui' )

	# connect base button
	pm.button( "ofb_selectBase_btn", edit=True, command = "offsetBlends.addToTextField('ofb_base_tf')" )

	# connect modified button
	pm.button( "ofb_selectModified_btn", edit=True, command = "offsetBlends.addToTextField('ofb_modified_tf')" )

	# connect  object to change buttons
	pm.button( "ofb_selectGeos_btn", edit=True, command = "offsetBlends.addToTextScroll('ofb_geos_tsl')" )

	# connect  apply change buttons
	pm.button( "ofb_apply_btn", edit=True, command = "offsetBlends.OffsetBlends()" )

	# show ui
	pm.showWindow( uiFile )
Пример #3
0
def UI():
    # find ui files
    ehm_uiPath = pm.internalVar(uad=True) + 'scripts/ehm_tools/ui/'

    # delete window if exists
    if pm.window('offsetBlends.ui', q=True, exists=True):
        pm.deleteUI('offsetBlends.ui')

    # load ui
    uiFile = pm.loadUI(uiFile=ehm_uiPath + 'offsetBlends.ui')

    # connect base button
    pm.button("ofb_selectBase_btn",
              edit=True,
              command="offsetBlends.addToTextField('ofb_base_tf')")

    # connect modified button
    pm.button("ofb_selectModified_btn",
              edit=True,
              command="offsetBlends.addToTextField('ofb_modified_tf')")

    # connect  object to change buttons
    pm.button("ofb_selectGeos_btn",
              edit=True,
              command="offsetBlends.addToTextScroll('ofb_geos_tsl')")

    # connect  apply change buttons
    pm.button("ofb_apply_btn",
              edit=True,
              command="offsetBlends.OffsetBlends()")

    # show ui
    pm.showWindow(uiFile)
Пример #4
0
def find_malware_files():
    """
    Collect all  script files that breed the malware.

    :rtype: list of path.Path
    """
    maya_user_dir = path.Path(pm.internalVar(userAppDir=True))
    user_setup_mel = maya_user_dir / 'scripts' / 'userSetup.mel'
    user_setup_py = maya_user_dir / 'scripts' / 'userSetup.py'
    user_setup_mel_data = util.read_file_text(
        user_setup_mel) if user_setup_mel.exists() else ''
    user_setup_py_data = util.read_file_text(
        user_setup_py) if user_setup_py.exists() else ''
    vaccine_py = maya_user_dir / 'scripts' / 'vaccine.py'
    vaccine_pyc = maya_user_dir / 'scripts' / 'vaccine.pyc'

    malware_files = []
    if 'fuck_All_U' in user_setup_mel_data:
        malware_files.append(user_setup_mel)
    if 'leukocyte' in user_setup_py_data and 'vaccine' in user_setup_py_data:
        malware_files.append(user_setup_py)
    if os.path.exists(vaccine_py):
        malware_files.append(vaccine_py)
    if os.path.exists(vaccine_pyc):
        malware_files.append(vaccine_pyc)

    return malware_files
Пример #5
0
    def exportPref(cls, data, labelObject, buttonObject, keyframingButtonGrp):
        ''' Save user preferences to file. Call applyPref().
        
        :param data: dictionary. Main ui button's colors, labels... keyframing preference.
        :param labelObject: list of the 6 color key label objects from settings ui.
        :param buttonObject: list of the 6 color key buttons objects from settings ui.
        :param keyframingButtonGrp: the keyframing option buttonGrp object from settings ui.
        '''

        # Labels
        for i, j in enumerate(labelObject):
            data['color%s' % str(i + 1)][0] = j.text()

        # Colors
        for i, j in enumerate(buttonObject):
            data['color%s' % str(i + 1)][1] = (j.property('rgb')[0],
                                               j.property('rgb')[1],
                                               j.property('rgb')[2])

        # Keyframing option
        data['keyframing'] = keyframingButtonGrp.checkedId()

        prefDir = pmc.internalVar(userPrefDir=True)
        prefFile = prefDir + prefFileName
        with open(prefFile, 'wb') as fh:
            pickle.dump(data, fh, pickle.HIGHEST_PROTOCOL)

        ColorKey.applyPref(data)
Пример #6
0
    def __init__(self, parent):
        super(AboutMeDialog, self).__init__(parent)

        self.setLayout(qg.QStackedLayout(self))
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.setFixedWidth(800)
        self.setFixedHeight(440)
        self.setStyleSheet("background-color: rgba(1,1,1,200);")

        self.setAttribute(qc.Qt.WA_DeleteOnClose)
        self.setModal(True)

        route = os.path.join(pm.internalVar(usd=1), 'HitchAnimationModule', 'Icons', 'Hitch_UI_aboutMe.jpg')
        pixmap = qg.QPixmap(route)
        scaled = pixmap.scaled(self.width(), self.height(), qc.Qt.KeepAspectRatio, qc.Qt.SmoothTransformation)

        self.frame = qg.QLabel()
        self.frame.setPixmap(scaled)
        self.frame.setSizePolicy(qg.QSizePolicy.Expanding, qg.QSizePolicy.Expanding)

        self.layout().addWidget(self.frame)

        frame_lyt = qg.QVBoxLayout(self.frame)
        frame_lyt.setContentsMargins(0, 0, 0, 0)

        self.layout().setStackingMode(qg.QStackedLayout.StackAll)

        self.close_btn = button.CloseButton()
        self.close_btn.setParent(self)
        self.close_btn.clicked.connect(lambda: self.close())

        self.show()
 def getDirectory(self):
     #  gives us back the name of our library directory and create it if it doesn't exist
     directory = os.path.join(pm.internalVar(userAppDir=True),
                              'lightManager')
     if not os.path.exists(directory):
         os.mkdir(directory)
     return directory
Пример #8
0
 def _saveSettings(self, *args):
     tempDir = pm.internalVar(userTmpDir=True)
     #--- Get tabs in the layout
     for sLayout in self.shelfTabs:
         if '(Deleted)' not in sLayout:
             pm.saveShelf(
                 shelf,
                 (tempDir + sLayout.split('|')[-1] + '_FloatingShelf'))
Пример #9
0
def showMessageDialog():
    fileName = time.strftime("%Y%m%d.%H%M") + ".ma"
    filePath = os.path.join(pm.internalVar(utd=1), fileName)
    pm.confirmDialog(
        icon="warning",
        m="Fatal Error. Attempting to save in {0}".format(filePath),
        t="maya",
        button=["OK"],
        ma="left")
Пример #10
0
 def __config_dumping(self):
     userPrefPath = pm.internalVar(upd=True)
     configDir = os.path.join(userPrefPath, CONFIG_DIR)
     configFile = os.path.join(configDir, CONFIG_FILE)
     if not os.path.exists(configDir):
         os.makedirs(configDir)
     # -- Write 2 File -- #
     with open(configFile.replace('\\', '/'), 'wb') as f:
         f.write(json.dumps(self.config, ensure_ascii=True, indent=4))
Пример #11
0
    def __init__(self, parent=maya_main_window()):
        # call the parent class and pass in the parent object
        super(DSL, self).__init__(parent)

        # we have possible root paths saved in a json file
        self.preferences_file = pm.internalVar(
            userPrefDir=True) + '/dsl_preferences.json'
        if not os.path.isfile(self.preferences_file):
            # if we don't have a preference file save one
            self.save_preferences({
                'folders': '',
                'default_folder': '',
                'position': '',
                'dockable': False,
                'docking_position': ''
            })

        self.current_dir = None

        # general window setup
        self.setWindowTitle('DSL Version 3.0')
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        # create fonts
        self.title_font = QtGui.QFont()
        self.title_font.setPointSize(24)
        self.title_font.setBold(True)

        self.empty_font = QtGui.QFont()
        self.empty_font.setPointSize(12)
        self.empty_font.setBold(True)

        # create a main layout
        self.main_layout = QtWidgets.QVBoxLayout()

        # add a menu bar and actions
        self.menu_bar = QtWidgets.QMenuBar(self)
        self.file_menu = self.menu_bar.addMenu('File')
        self.preferences_action = QtWidgets.QAction(
            'Preferences',
            self,
            statusTip='List of available folders',
            triggered=self.show_folder_list)

        self.refresh = QtWidgets.QAction('Refresh',
                                         self,
                                         statusTip='Refresh script list',
                                         triggered=self.load_scripts)

        self.file_menu.addAction(self.preferences_action)
        self.file_menu.addAction(self.refresh)

        # load the scripts from the root dir
        self.load_scripts()
Пример #12
0
    def __config_loading(self):
        userPrefPath = pm.internalVar(upd=True)
        configFile = os.path.join(userPrefPath, CONFIG_DIR, CONFIG_FILE)
        if not os.path.exists(configFile):
            self.config.setdefault('root', '')
            return

        with open(configFile.replace('\\', '/'), 'rb') as f:
            self.config = json.load(f) or {}
            if self.config:
                self.pathing = self.config['root']
Пример #13
0
 def location( self, update=None ):
     """Location of the script editor files.
     
     update:
         Refresh the location. If left empty, return the stored location.
          - Boolean
     """
     #Return location of script editor files
     if update is None:
         return pm.optionVar[self.locationName]
     
     #Refresh location of script editor files
     pm.optionVar[self.locationName] = pm.internalVar( userPrefDir=True )
Пример #14
0
    def get_temp_dirname(cls, dir_name):
        temp_dir = Config.get(TestVars.temp_dir)
        if not temp_dir:
            temp_dir = pm.internalVar(utd=1)

        path = os.path.join(temp_dir, dir_name)
        count = 0
        while os.path.exists(path):
            count += 1
            path = os.path.join(temp_dir, "{0}{1}".format(dir_name, count))
        cls.dirs_created.append(path)

        return path
Пример #15
0
def UI():
    if pm.window('pbudk', exists=True):
        pm.deleteUI('pbudk')

    optspath = '%s/pbUDK.json' % pm.internalVar(usd=True)
    defaultdata = {
        'phyType':
        1,
        'maxVerts':
        32,
        'center':
        True,
        'child':
        True,
        'fbxPath':
        '%sdata/' % pm.workspace(q=True, rd=True),
        'presetFile':
        '%s/UDKexport/UDK-FBX.fbxexportpreset' % pm.internalVar(usd=True),
        'version':
        version,
        'prefix':
        False,
        'prefix_text':
        '',
        'suffix':
        False,
        'suffix_text':
        ''
    }

    with pm.window('pbudk',
                   title="{0} - {1}".format(title, version),
                   width=250,
                   sizeable=True) as window:
        with pm.columnLayout():
            opts = JSONDict(optspath, defaultdata)
            PhyUI(opts)
            FbxUI(opts)
        window.show()
def onMayaDroppedPythonFile(obj):
    """
    the onMayaDroppedPythonFile method
    this method name is recognized by maya and is being called when the file is dropped inside the viewport.

    creates a shelf button for the Image Card Importer tool.
    raises an error if the Image Card Importer folder is not located inside the scripts folder.

    """

    # get the dropped file location
    path = os.path.dirname(os.path.abspath(__file__))
    parent_path = os.path.abspath(os.path.join(path, os.pardir))

    # get maya scripts folder path
    scripts_path = pm.internalVar(usd=True)
    scripts_path = scripts_path.replace("/", "\\")

    if scripts_path[-1] == "\\":
        scripts_path = scripts_path[:-1]

    # compare the paths and if the current file path is not maya scripts folder, raise an error.
    if parent_path != scripts_path:
        error_string = "the image_card_importer folder is inside in the incorrect folder.\nthe correct folder is: " + scripts_path
        pm.confirmDialog(title='Error',
                         message=error_string,
                         button='OK',
                         defaultButton='OK',
                         cancelButton='OK')

    else:

        icon_directory = os.path.join(path, "icons")
        image_path = os.path.join(icon_directory,
                                  "image_card_importer_icon.png")

        # get current top shelf
        top_shelf = mel.eval('$nul = $gShelfTopLevel')

        # create a shelf button on current top shelf
        if pm.windows.tabLayout(top_shelf, e=1):
            pm.windows.shelfButton(
                parent=top_shelf + "|" +
                pm.windows.tabLayout(top_shelf, q=1, st=1),
                annotation='Image Card Importer',
                image1=image_path,
                command=
                "import image_card_importer.image_card_importer_tool as im\n"
                "win = im.window_ui()\n"
                "win.display()",
            )
Пример #17
0
def UI():
    if pm.window('pbudk', exists=True):
        pm.deleteUI('pbudk')

    optspath = '%s/pbUDK.json' % pm.internalVar(usd=True)
    defaultdata = {'phyType': 1,
                   'maxVerts': 32,
                   'center': True,
                   'child': True,
                   'fbxPath': '%sdata/' % pm.workspace(q=True, rd=True),
                   'presetFile': '%s/UDKexport/UDK-FBX.fbxexportpreset' % pm.internalVar(usd=True),
                   'version': version,
                   'prefix': False,
                   'prefix_text': '',
                   'suffix': False,
                   'suffix_text': ''}

    with pm.window('pbudk', title="{0} - {1}".format(title, version), width=250, sizeable=True) as window:
        with pm.columnLayout():
            opts = JSONDict(optspath, defaultdata)
            PhyUI(opts)
            FbxUI(opts)
        window.show()
Пример #18
0
	def ioAttrPreset(self, nodeType, save):
		"""doc"""
		presetLocalDir = str(pm.internalVar(userPresetsDir= 1))
		presetVar = presetLocalDir + '%sPreset_%s.mel'
		# save out presets
		presetDict = {}
		for node in pm.ls(type= nodeType):
			presetName = node.name()
			if save:
				pm.nodePreset(save= [node, presetName])
			else:
				pm.nodePreset(load= [node, presetName])
			presetDict[node.name()] = presetVar % (nodeType, presetName)

		return presetDict
Пример #19
0
    def getDirectory(self):
        """
		Get directory of our library
			
		Returns:
			directory(str) - a path to the directory
			
		"""
        # Write their properities into the directory
        directory = os.path.join(pm.internalVar(userAppDir=True),
                                 'lightManager')
        # Check if it exists or not
        if not os.path.exists(directory):
            os.mkdir(directory)
        return directory
Пример #20
0
def check_local_package(installed_title):
    """Check installed package in Maya user application directory.

    :return: True if its exists, Falser otherwise
    :rtype: bool
    """
    user_app_dir = path.Path(pm.internalVar(uad=True))
    installed_dir = user_app_dir / installed_title

    if installed_dir.isfile():
        return False
    elif installed_dir.isdir():
        return True
    else:
        return False
Пример #21
0
    def __init__(self, dock=False):
        ## GET SETTINGS
        self.settings = settings.get()
        if not self.settings.DEFAULT_DIR_KEY:
            self.lastDir = self.getDirectory()
        else:
            self.lastDir = self.settings.DEFAULT_DIR_KEY

        if dock:
            parent = getDock()
        else:
            deleteDock()
            try:
                pm.deleteUI('re_manager')
            except:
                logger.debug('No previous UI exists')

            parent = QtWidgets.QMainWindow(parent=getMayaMainWindow())
            parent.setObjectName('re_manager')
            parent.setWindowTitle('RE Engine Tool')
        super(RE_Manager, self).__init__(parent=parent)

        self.setupUi(parent)
        self.setup_buttons()
        self.parent().layout().addWidget(self)
        self.parent = parent
        parent.setWindowTitle("RE Engine Motion Tool " + TOOL_VERSION)

        self.recentFileActs = []

        for i in range(self.settings.RECENT_FILES_MAX):
            self.recentFileActs.append(
                QtWidgets.QAction(parent,
                                  visible=False,
                                  triggered=self.openRecentFile))
            self.menuRecent_Files.addAction(self.recentFileActs[i])

        self.recent_files_update()

        #self.lineEditRawDepo.setText(self.settings.repopath)
        #self.checkBoxImportFace.setChecked(self.settings.importFacePoses)
        directory = os.path.join(pm.internalVar(userAppDir=True),
                                 're_engine_working')

        ##DEBUG
        #self.populate_animSet("F:\\RE3R_MODS\\maya files\\010 anims\\em0000_es_pl_bite.motlist.99")
        if not dock:
            parent.show()
Пример #22
0
    def get_temp_filename(cls, file_name):
        temp_dir = Config.get(TestVars.temp_dir)
        if not temp_dir:
            temp_dir = pm.internalVar(utd=1)
        if not os.path.exists(temp_dir):
            os.makedirs(temp_dir)

        base_name, ext = os.path.splitext(file_name)
        path = os.path.join(temp_dir, base_name + ext)
        count = 0
        while os.path.exists(path):
            count += 1
            path = os.path.join(temp_dir, "{0}{1}{2}".format(base_name, count, ext))
        cls.files_created.append(path)

        return path
Пример #23
0
    def getDirectory(self, type):
        """
        set and get the rig Log directory
        :return: rig log directory
        """
        if type == 'rig':
            fileName = 'rigLogFiles'
        elif type == 'twist':
            fileName = 'twistLogFiles'
        else:
            logger.info('Unknow directory type name, please check again!')
            return

        logDir = os.path.join(pm.internalVar(userAppDir=1), fileName)
        if not os.path.exists(logDir):
            os.mkdir(logDir)
        return logDir
Пример #24
0
    def importPref(cls):
        '''Import user preferences from file. If preference file doesn't exist, use default values.'''

        prefDir = pmc.internalVar(userPrefDir=True)
        if prefFileName in os.listdir(prefDir):
            prefFile = prefDir + prefFileName
            with open(prefFile, 'rb') as fh:
                data = pickle.load(fh)
        else:
            data = {
                'color1': ['', (255, 255, 0), '_1'],
                'color2': ['', (255, 0, 0), '_2'],
                'color3': ['', (0, 255, 0), '_3'],
                'color4': ['', (255, 0, 255), '_4'],
                'color5': ['', (0, 0, 255), '_5'],
                'color6': ['', (0, 255, 255), '_6'],
                'keyframing': -2,
            }
        return data
Пример #25
0
def uninstall(installed_title):
    """Uninstall FrMaya package.

    :arg installed_title: FrMaya package title name.
    :type installed_title: str
    """
    assert installed_title, 'Package title not found!!!'
    assert installed_title != 'maya', '{} is not package!!'.format(
        installed_title)
    # Maya user application directory
    user_app_dir = path.Path(pm.internalVar(uad=True))
    # modules dir
    module_dir = user_app_dir / 'modules'
    module_file = module_dir / '{}.mod'.format(installed_title)
    if module_file.exists():
        module_file.remove()

    # installed package
    installed_pkg = user_app_dir / installed_title
    if installed_pkg.exists():
        shutil.rmtree(installed_pkg, ignore_errors=True)
Пример #26
0
    def __init__(self, parent=None):
        import os
        import pymel.core as pm

        # initialize the QlistView
        QtGui.QTreeWidget.__init__(self, parent)

        self.GData = g.GData()
        self.dropOp = QtCore.pyqtSignal(QtCore.Qt.KeyboardModifiers, bool, str)

        #locate the directory where all of the images for the UI live
        ScriptDir = pm.internalVar(uad = True)
        self.imgDirectory = str(ScriptDir+"/scripts/pipeline/general/filebrowse/images/")

        self.setAcceptDrops(True)
        self.setDragEnabled(False)
        self.setDragDropMode(QtGui.QAbstractItemView.DropOnly)

        self.setColumnCount(1)
        self.setHeaderHidden(True)
        self.reloadBookmarks()
Пример #27
0
def install(source_path, package_title='', local_install=False):
    """Install FrMaya package.

    :arg source_path: Downloaded or cloned FrMaya package absolute path.
    :type source_path: str or path.Path
    :key package_title: Package name.
    :type package_title: str
    :key local_install: If True, FrMaya package will be copied into maya user application directory.
    :type local_install: bool
    :rtype: bool
    """
    frmaya_content = [
        'FrMaya', 'MayaMenubar', 'RigData', 'startup', 'LICENSE.txt',
        'README.md'
    ]
    source_path = path.Path(source_path).abspath()
    if package_title:
        installed_title = package_title
    else:
        installed_title = source_path.name
    assert source_path.exists(), 'Source path did not exist!!!'
    assert installed_title, 'Package title not found!!!'
    for each in frmaya_content:
        sub_item = source_path / each
        assert sub_item.exists(
        ), '{} did not exists, make sure its exists!!'.format(sub_item)

    # Maya user application directory
    user_app_dir = path.Path(pm.internalVar(uad=True))
    # create modules dir
    module_dir = user_app_dir / 'modules'
    if not module_dir.exists():
        module_dir.mkdir()

    # uninstall first if any
    uninstall(installed_title)
    if local_install:
        # FrMaya script folder path
        target_dir = user_app_dir / installed_title
        # create FrMaya root dir
        if not target_dir.exists():
            target_dir.mkdir()
        # copy all sub content into target_dir
        for each in frmaya_content:
            src = source_path / each
            tgt = target_dir / each
            if src.isdir():
                shutil.copytree(src.abspath(), tgt.abspath())
            elif src.isfile():
                shutil.copy(src.abspath(), tgt.abspath())
    else:
        target_dir = source_path

    # write module file
    module_file = module_dir / '{}.mod'.format(installed_title)
    with open(module_file, 'w') as ss:
        ss.write('+ FrMaya any {}\n'.format(target_dir))
        ss.write('scripts+:=startup\n')
        ss.write('PYTHONPATH+:=\n')
        ss.write('PYTHONPATH+:=startup\n')
        ss.write('MAYA_SCRIPT_PATH+:=startup\n')
        ss.write('FR_MYMENUBAR+:=MayaMenubar\n')
        ss.write('FR_CONTROLCURVE+:=RigData\\ControlCurve\n')

    return True
Пример #28
0
import os
import distutils
import pymel.core as pm
from PySide2 import QtWidgets


def onMayaDroppedPythonFile(*args):
    pass

script_dir = pm.internalVar(usd=True)
icon_dir = pm.internalVar(ubd=True)
dl_dir = os.path.dirname(__file__)

distutils.dir_util.copy_tree(os.path.join(dl_dir, 'scripts'), os.path.dirname(script_dir))
distutils.dir_util.copy_tree(os.path.join(dl_dir, 'icons'), os.path.dirname(icon_dir))

shelves = pm.tabLayout(pm.getMelGlobal('string', '$gShelfTopLevel'), query=True, childArray=True)
current = shelves.index(pm.tabLayout(pm.getMelGlobal('string', '$gShelfTopLevel'), query=True, selectTab=True))
itm, accepted = QtWidgets.QInputDialog().getItem(None, 'Shelf Button', 'Which Shelf Do You Wish to Add the Button To?',
                                                 shelves, editable=False, current=current)

if accepted:
    pm.shelfButton(style="iconOnly", parent=itm, image='na_scratch_paper', label='Scratch Paper',
                   command='import na_scratch_paper\nna_scratch_paper.run_maya()')
Пример #29
0
def getDefaultProject():
    """ Returns the Default Project Directory """
    return pm.internalVar(uwd=1)  # default project
Пример #30
0
def UI():
    
    # kill window if it already exists
    if pm.window('varFkUI', exists = True):
        pm.deleteUI('varFkUI')
    
    # build window
    varFkWindow = pm.window('varFkUI', title = 'Variable Fk Rigger', widthHeight=(365.0, 340.0), sizeable=False, minimizeButton=True, maximizeButton=False)
    
    # create tabLayout
    tabs = pm.tabLayout(imw = 5, imh = 5)
    
    # create tabs
    form = pm.formLayout(numberOfDivisions=100, w = 365, h = 340, parent = tabs)
    pm.tabLayout(tabs, edit = True, tabLabel = (form, 'VarFk Rigger'))
    info = pm.formLayout(numberOfDivisions=100, w = 365, h = 340, parent = tabs)
    pm.tabLayout(tabs, edit = True, tabLabel = (info, 'Help'))
    
    # fill info tab
    pm.setParent ( info )
    
    # Creating Element scrollField_info
    infotext = 'Variable FK Autorigger \nVersion: 1.00 \nby Julian "fleity" Oberbeck. \n\nBasic variable FK concept by Jeff Brodsky (https://vimeo.com/72424469). \n\n\nVariable FK Rigs allow moving a FK-control along a joint chain, their influence being based on the distance to the joints. \n\n How to use: \n 1. Insert the name of the input curve. \n 2. Enter a name for the rig. \n 3. Choose number of controls. \n 4. Press "Build."'

    # Creating Element scrollField_infotext
    scrollField_infotext = pm.scrollField ( text = infotext, w = 340, h = 295, editable = False, wordWrap = True )
    pm.formLayout( info, edit=True, attachForm=[( scrollField_infotext, 'top', 10), ( scrollField_infotext, 'left', 10)] )

    # fill main utility tab
    pm.setParent( form )
    
    # Creating Element img_banner
    imagePath = pm.internalVar(upd = True) + '/icons/varFk.png' # old
    imagePath = '/'.join( __file__.split('\\')[:-1] ) + '/varFk.png'
    img_banner = pm.image( w = 365, h = 110, image = imagePath )
    pm.formLayout( form, edit=True, attachForm=[( img_banner, 'top', 0), ( img_banner, 'left', -5)] )
    # =========================================
    # Creating Element layout_curve_tools
    shelfLayout_curveTools = pm.shelfTabLayout( 'shelfCurves', w = 225, h = 50, tabsVisible = False )
    pm.setParent( shelfLayout_curveTools )
    pm.formLayout( form, edit=True, attachForm=[( shelfLayout_curveTools, 'top', 97), ( shelfLayout_curveTools, 'left', 70)] )
    rowLayout_curveTools = pm.rowLayout( 'rowLayout_curveTools', w = 200, h = 45, numberOfColumns = 4, cw4 = [40,40,40,40], ct4 = ['left', 'left', 'left', 'left'], co4 = [10,10,10,10] )
    pm.setParent( rowLayout_curveTools )
    # =========================================
    # Creating Elements curve tool buttons
    button_CVCurveTool = pm.iconTextButton( 'button_CVCurveTool', w = 40, h = 40, mw = 2, mh = 2, image = 'curveCV.png', command = pm.Callback(pm.runtime.CVCurveTool, ), doubleClickCommand = pm.Callback(pm.runtime.CVCurveToolOptions, ) )
    button_EPCurveTool = pm.iconTextButton( 'button_EPCurveTool', w = 40, h = 40, mw = 2, mh = 2, image = 'curveEP.png', command = pm.Callback(pm.runtime.EPCurveTool, ), doubleClickCommand = pm.Callback(pm.runtime.EPCurveToolOptions, ) )
    button_PencilCurveTool = pm.iconTextButton( 'button_PencilCurveTool', w = 40, h = 40, mw = 2, mh = 2, image = 'pencil.png', command = pm.Callback(pm.runtime.PencilCurveTool, ), doubleClickCommand = pm.Callback(pm.runtime.PencilCurveToolOptions, ) )
    button_BezierCurveTool = pm.iconTextButton( 'button_BezierCurveTool', w = 40, h = 40, mw = 2, mh = 2, image = 'curveBezier.png', command = pm.Callback(pm.runtime.CreateBezierCurveTool, ), doubleClickCommand = pm.Callback(pm.runtime.CreateBezierCurveToolOptions, ) )
    # =========================================
    pm.setParent( form )
    # =========================================
    # Creating Element button_insertSelectedCurve
    button_insertSelectedCurve = pm.button( label='>', w=35, h=25, command=pm.Callback(insertFirstSelected, ) )
    pm.formLayout( form, edit=True, attachForm=[( button_insertSelectedCurve, 'top', 155), ( button_insertSelectedCurve, 'left', 55)] )
    # =========================================    
    # Creating Element input_inputCurve
    input_inputCurve = pm.textField('input_inputCurve', text='Draw a curve, 1 Joint per CV.', w=250, h=25)
    pm.formLayout( form, edit=True, attachForm=[( input_inputCurve, 'top', 155), ( input_inputCurve, 'left', 100)] )
    # =========================================
    # Creating Element text_IdName
    text_IdName = pm.text( label='Prefix Name:', align='right', recomputeSize=True, w=80, h=25)
    pm.formLayout( form, edit=True, attachForm=[( text_IdName, 'top', 190), ( text_IdName, 'left', 10)] )
    # =========================================
    # Creating Element input_IdName
    input_IdName = pm.textField('input_IdName', text='varFk', w=250, h=25)
    pm.formLayout( form, edit=True, attachForm=[( input_IdName, 'top', 190), ( input_IdName, 'left', 100)] )    
    # =========================================    
    # Creating Element text_numOfCtrls
    text_numOfCtrls = pm.text( label='# of Controls:', align='right', recomputeSize=True, w=80, h=25)
    pm.formLayout( form, edit=True, attachForm=[( text_numOfCtrls, 'top', 225), ( text_numOfCtrls, 'left', 10)] )
    # =========================================
    # Creating Element slider_numOfCtrls
    slider_numOfCtrls = pm.intSliderGrp('slider_numOfCtrls', f=True, min=1, max=10, fieldMinValue=1,fieldMaxValue=999, value=3, ann='Number of Controls', w=255, h=25)
    pm.formLayout( form, edit=True, attachForm=[( slider_numOfCtrls, 'top', 225), ( slider_numOfCtrls, 'left', 100)] )
    # =========================================
    # Creating Element button_build
    button_build = pm.button( label='Build', w=340, h=40, command = pm.Callback(buildVarFkFromUI, ))
    pm.formLayout( form, edit=True, attachForm=[( button_build, 'top', 265), ( button_build, 'left', 10)] )
    # =========================================
    
    pm.setParent( '..' )    

    # show window
    varFkWindow.show()
Пример #31
0
import os
import pymel.core as pm

MAYA_APP_PATH = str(pm.internalVar(uad=1))  # type: str
TMP_PATH = pm.internalVar(utd=1)  # type: str
USER_PREFS_PATH = pm.internalVar(upd=1)  # type: str
LUNA_ROOT_PATH = pm.moduleInfo(moduleName="luna", p=1)  # type: str # type: str
LOG_FILE = os.path.join(LUNA_ROOT_PATH, "luna.log")  # type: str
SHAPES_LIB_PATH = os.path.join(LUNA_ROOT_PATH, "res", "shapes")  # type: str
TEMPLATES_PATH = os.path.join(LUNA_ROOT_PATH, "res", "templates")  # type: str
EMPTY_SCENES_PATH = os.path.join(TEMPLATES_PATH, "emptyScenes")  # type: str
ICONS_PATH = os.path.join(LUNA_ROOT_PATH, "res", "images",
                          "icons")  # type: str
FALLBACK_IMG_PATH = os.path.join(LUNA_ROOT_PATH, "res", "images",
                                 "fallbacks")  # type: str
COMET_ORIENT_PATH = MAYA_APP_PATH + "scripts/comet/cometJointOrient.mel"  # type: str
DEFAULT_CONFIG_PATH = os.path.join(LUNA_ROOT_PATH, "configs",
                                   "default_config.json")  # type:str
CONFIG_PATH = os.path.join(LUNA_ROOT_PATH, "configs",
                           "config.json")  # type:str
EXTERNAL_TOOLS_REGISTER = os.path.join(LUNA_ROOT_PATH, "configs",
                                       "external_tools.json")  # type:str
TEST_DIR_PATH = os.path.join(LUNA_ROOT_PATH, "tests")  # type:str
PLUGINS_DIR_PATH = os.path.join(LUNA_ROOT_PATH, "plug-ins")  # type:str
EDITOR_PLUGINS_PATH = os.path.join(LUNA_ROOT_PATH, "luna_builder", "rig_nodes")


def get_icon_path(*path_parts):
    return os.path.join(ICONS_PATH, *path_parts)
Пример #32
0
import os
import sip

import pymel.core as pm
import maya.OpenMayaUI as mui
import pymel.api as api

from PyQt4 import QtGui, QtCore, uic

def getMayaWindow():
    'Get the maya main window as a QMainWindow instance'
    ptr = api.OpenMayaUI.MQtUtil_mainWindow()
    return sip.wrapinstance(long(ptr), QtCore.QObject)

#Get the absolute path to my ui file
uiFile = os.path.join(pm.internalVar(usd=True), 'src', 'ui', 'mouseCap.ui')
print 'Loading ui file:', os.path.normpath(uiFile)

#Load the ui file, and create my class
form_class, base_class = uic.loadUiType(uiFile)
class MouseCapWindow(base_class, form_class):
    def __init__(self, parent=getMayaWindow()):
        '''A custom window with a demo set of ui widgets'''
        #init our ui using the MayaWindow as parent
        super(base_class, self).__init__(parent)
        #uic adds a function to our class called setupUi, calling this creates all the widgets from the .ui file
        self.setupUi(self)
        self.setObjectName('myWindow')
        self.setWindowTitle("MouseCap 0.1.0")
        
        self.connect(self.xButton, QtCore.SIGNAL('clicked()'), self.addToX)
Пример #33
0
	def __init__(self):
		self.directory = "%s/nwModularRiggingTool" %pm.internalVar(userScriptDir = True)
		
		self.previousBlueprintListEntry = None
		self.previousBlueprintModule = None
		self.previousAnimationModule = None
		
		#baseIconsDir = "%s/Icons/" %self.directory
		baseIconsDir = "%s/Icons/" %os.environ["RIGGING_TOOL_ROOT"]
		
		self.selectedCharacter = self.FindSelectedCharacter()
		
		if self.selectedCharacter == None:
			return
		
		self.characterName = self.selectedCharacter.partition("__")[2]
		
		self.windowName = "%s_window" %self.characterName
		
		# Create UI
		self.UIElements = {}
		
		if pm.window(self.windowName, exists = True):
			pm.deleteUI(self.windowName)
		
		self.windowWidth = 420
		self.windowHeight = 730
		
		self.frameColumnHeight = 125
		
		self.UIElements["window"] = pm.window(self.windowName, width = self.windowWidth, height = self.windowHeight, title = "Animation UI: %s" %self.characterName, sizeable = False)
		
		self.UIElements["topColumnLayout"] = pm.columnLayout(adjustableColumn = True, rowSpacing = 3, parent = self.UIElements["window"])
		
		buttonWidth = 32
		columnOffset = 5
		buttonColumnWidth = buttonWidth + (2 * columnOffset)
		textScrollWidth = (self.windowWidth - buttonColumnWidth - 8) / 2
		
		self.UIElements["listboxRowLayout"] = pm.rowLayout(numberOfColumns = 3, columnWidth3 = [textScrollWidth, textScrollWidth, buttonColumnWidth], columnAttach = ([1, "both", columnOffset], [2, "both", columnOffset], [3, "both", columnOffset]), parent = self.UIElements["topColumnLayout"])
		
		self.UIElements["blueprintModule_textScroll"] = pm.textScrollList(numberOfRows = 12, allowMultiSelection = False, selectCommand = self.RefreshAnimationModuleList, parent = self.UIElements["listboxRowLayout"])
		self.InitializeBlueprintModuleList()
		
		self.UIElements["animationModule_textScroll"] = pm.textScrollList(numberOfRows = 12, allowMultiSelection = False, selectCommand = self.SetupModuleSpecificControls, parent = self.UIElements["listboxRowLayout"])
		
		self.UIElements["buttonColumnLayout"] = pm.columnLayout(parent = self.UIElements["listboxRowLayout"])
		self.UIElements["pinButton"] = pm.symbolCheckBox(onImage = "%s_pinned.xpm" %baseIconsDir, offImage = "%s_unpinned.xpm" %baseIconsDir, width = buttonWidth, height = buttonWidth, onCommand = self.DeleteScriptJob, offCommand = self.SetupScriptjob, parent = self.UIElements["buttonColumnLayout"])
		
		if pm.objExists("%s:non_blueprint_grp" %self.selectedCharacter):
			value = pm.getAttr("%s:non_blueprint_grp.display" %self.selectedCharacter)
			self.UIElements["non_blueprintVisibility"] = pm.symbolCheckBox(image = "%s_shelf_character.xpm" %baseIconsDir, value = value, width = buttonWidth, height = buttonWidth, onCommand = self.ToggleNonBlueprintVisibility, offCommand = self.ToggleNonBlueprintVisibility, parent = self.UIElements["buttonColumnLayout"])
		
		value = pm.getAttr("%s:character_grp.animationControlVisibility" %self.selectedCharacter)
		self.UIElements["animControlVisibility"] = pm.symbolCheckBox(image = "%s_visibility.xpm" %baseIconsDir, value = value, width = buttonWidth, height = buttonWidth, onCommand = self.ToggleAnimControlVisibility, offCommand = self.ToggleAnimControlVisibility, parent = self.UIElements["buttonColumnLayout"])
		
		self.UIElements["deleteModuleButton"] = pm.symbolButton(image = "%s_shelf_delete.xpm" %baseIconsDir, width = buttonWidth, height = buttonWidth, enable = False, command = self.DeleteSelectedModule, parent = self.UIElements["buttonColumnLayout"])
		self.UIElements["duplicateModuleButton"] = pm.symbolButton(image = "%s_duplicate.xpm" %baseIconsDir, width = buttonWidth, height = buttonWidth, enable = False, parent = self.UIElements["buttonColumnLayout"])
		
		
		pm.separator(style = "in", parent = self.UIElements["topColumnLayout"])
		
		self.UIElements["activeModuleColumn"] = pm.columnLayout(adjustableColumn = True, parent = self.UIElements["topColumnLayout"])
		self.SetupActiveModuleControls()
		
		pm.separator(style = "in", parent = self.UIElements["topColumnLayout"])
		
		self.UIElements["matchingButton"] = pm.button(label = "Match Controls to Result", enable = False, parent = self.UIElements["topColumnLayout"])
		
		pm.separator(style = "in", parent = self.UIElements["topColumnLayout"])
		
		
		pm.rowColumnLayout("module_rowColumn", numberOfRows = 1, rowAttach = [1, "both", 0], rowHeight = [1, self.windowHeight - 395], parent = self.UIElements["topColumnLayout"])
		
		self.UIElements["moduleSpecificControlsScroll"] = pm.scrollLayout(width = self.windowWidth + 10, horizontalScrollBarThickness = 0, parent = "module_rowColumn")
		
		self.UIElements["moduleSpecificControlsColumn"] = pm.columnLayout(columnWidth = self.windowWidth, columnAttach = ["both", 5], parent = self.UIElements["moduleSpecificControlsScroll"])
		
		
		self.RefreshAnimationModuleList()
		
		self.SetupScriptjob()
		
		
		pm.showWindow(self.UIElements["window"])
		
		self.SelectionChanged()
Пример #34
0
 def _saveSettings(self,*args):
     tempDir = pm.internalVar( userTmpDir=True )
     #--- Get tabs in the layout
     for sLayout in self.shelfTabs:
         if '(Deleted)' not in sLayout:
             pm.saveShelf( shelf, (tempDir + sLayout.split('|')[-1]+'_FloatingShelf') );        
Пример #35
0
reload(TopPanel)
reload(viewportClass)
reload(button)
reload(spliter)
reload(HeadPicker)
reload(BodyPicker)
reload(Tabs)
reload(LeftPanel)

#---------------------------------------------------------------------------------#
HITCH_UI = None
windowTitle = "Hitch Animation Manager"
windowObject = "HitchAnimationUI_Object"

STYLESHEET = os.path.join(pm.internalVar(usd=1), 'HitchAnimationModule', 'StyleSheets', 'scheme.txt')
HEADERPIXMAP = os.path.join(pm.internalVar(usd=1), 'HitchAnimationModule', 'Icons', 'hitchNameUIHeaderNoBackground.png')
WINDOWICON = os.path.join(pm.internalVar(usd=1), 'HitchAnimationModule', 'Icons', 'Hitch_FaceForLogo.png')

#---------------------------------------------------------------------------------#
# delete ANY maya child with given object name to mantain clean the memory
#


def deleteFromGlobal():
    mayaMainWindowPtr = mui.MQtUtil.mainWindow()
    mayaMainWindow = shi.wrapInstance(long(mayaMainWindowPtr), qg.QMainWindow)  # Important that it's QMainWindow, and not QWidget
    try:
        # Go through main window's children to find any previous instances
        for obj in mayaMainWindow.children():
            # print(obj.objectName())
Пример #36
0
library or make no selection to save the whole scene.  Name model appropriately.  To overwrite a model, save new model
with same name.  Output is a .ma file located in a default directory.  If a model file is deleted from the default
directory it's library membership will be revoked next time the app is executed.  The model file will still be present
in the directory, but no longer loaded into the library.  To load or delete a model from the library, select the model's
icon in the gui and click the appropriate action.  Hover over an icon to see more information on the model.
"""

import pymel.core as pmc
import os
import json
import pprint
import maya.OpenMayaUI as omui
from PySide import QtGui, QtCore
from shiboken import wrapInstance

USER_APP_DIR = pmc.internalVar(userAppDir=True)
DEFAULT_DIRECTORY = os.path.join(USER_APP_DIR, 'modelLibrary')
JSON_PATH = os.path.join(DEFAULT_DIRECTORY, 'modelLibrary.json')
UNIQUE_HANDLE = 'ModelLibWindow'


def get_maya_main_window():
    main_win_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(main_win_ptr), QtGui.QWidget)


class ModelLibUI(QtGui.QDialog):

    SIZE = 64
    BUFFER = 20
Пример #37
0
 def getDirectory(self):
     directory = os.path.join(pm.internalVar(userAppDir=True),
                              'lightManager')
     if not os.path.exists(directory):
         os.mkdir(directory)
     return directory
              
Note : This file lives in the maya script directory.

"""
#===============================================================================
# IMPORT    
#===============================================================================
import pymel.core as pm
import os, sys, logging
import json

#===============================================================================
# Environment Variables
#===============================================================================
config_filename = "pixo_rigging_config.json"
pm.mel.putenv("PIXO_RIGGING_CONFIG_PATH", os.path.join(pm.internalVar(userScriptDir=True), config_filename))

#===============================================================================
# FOLDERS AND PATHS
#===============================================================================
TOOL_FOLDER = "tool"
SYSTEM_FOLDER = "system"
SETUP_FOLDER = 'setup'
PATCH_FOLDER = 'patch'
PLUGIN_FOLDER = 'plugin'
DATA_FOLDER = 'data'
MENU_FOLDER = "menu"

#===============================================================================
# LOGGER
#===============================================================================
Пример #39
0
Author: Ehsan HM ( [email protected] )

Script Name: ExportImportAnim()

Version: 1.0

What does this do: exports and imports animation of selected objects.


'''

import pymel.core as pm
import sys
import os

uad = pm.internalVar( uad=True )
import pymel.core as pm
from functools import partial

class ExportImportAnim():
	
	def __init__(self, *args, **kwargs):
	
		if args or kwargs:
			self.importAnim(*args, **kwargs)
		else:
			self.UI()

			
	def UI(self):
		
Пример #40
0
Author: Ehsan HM ( [email protected] )

Script Name: ExportImportAnim()

Version: 1.0

What does this do: exports and imports animation of selected objects.


'''

import pymel.core as pm
import sys
import os

uad = pm.internalVar(uad=True)
import pymel.core as pm
from functools import partial


class ExportImportAnim():
    def __init__(self, *args, **kwargs):

        if args or kwargs:
            self.importAnim(*args, **kwargs)
        else:
            self.UI()

    def UI(self):

        # create window
Пример #41
0
def AutoRig_UI():
    
    if pm.window("AutoRig_JT", q=True, exists = True):
            pm.deleteUI("AutoRig_JT")
    
    windowUI = pm.window("AutoRig_JT",titleBarMenu=True, menuBar=True, mxb = False, t="AutoRig_JT", w = 300, h = 500, sizeable = False, bgc=[0.15,0.15,0.15],maximizeButton=False)
	
    pm.menu( label='File', tearOff=True )
    pm.menuItem( label='Quit', c = partial(quit, "AutoRig_JT"))
    pm.menu( label='Help', helpMenu=True )
    pm.menuItem( 'Application..."', label='About Creator', c = about )
    pm.menuItem( 'Instructions', label='Instructions', c = instructions )
	
		
    mainLayout = pm.columnLayout(adj = True, w=300, h=700)

    # unique UI stuff

    imagePath = pm.internalVar(upd = True) + "icons/autoRig_banner.jpg"
    pm.image(w = 300, h = 100,image = imagePath, parent = mainLayout)
    pm.separator(style = 'none', h=20)

    pm.rowColumnLayout(nc = 2, cw = [(1,100),(2,200)],parent = mainLayout, columnOffset = ([(1,"left",10),(2,"left",0)]))

    pm.text(l='    Rig_Prefix : ')

    RigPrefix = pm.textFieldGrp("RigPrefix",tx='Character_',w=80) 

    pm.separator(style = 'none', h=20)
    pm.separator(style = 'none', h=20)
	
    
	
    pm.text(l='Spine Joints : ')
    spineNumberField = pm.intFieldGrp("spineNumberField",numberOfFields=1,v1=3,w=190)
	
    pm.setParent(u=True)
	
	
    pm.separator(style = 'none', h=20)
    pm.separator(style = 'none', h=20)

    pm.separator(style = 'none',h=20)
    pm.button(l='Create Reference Skeleton',c=referenceSkeleton, w=190,h=40,bgc=[0.2,0.2,0.2])

    pm.separator(style = 'none', h=20)

    pm.button(l='Mirror Locators (X+ to -X) (edit)', c=mirrorLocators, w=190, h=40, bgc=[0.2, 0.2, 0.2])

    pm.separator(style='none', h=20)
    
    pm.button(l='Create Joint Skeleton (edit)', c=jointSkeleton, w=190, h=40, bgc=[0.2, 0.2, 0.2])

    pm.separator(style='none', h=20)
    
    pm.radioButtonGrp('ZAxisOption', label='Z Align Axis', labelArray3=['X', 'Y', 'Z'], numberOfRadioButtons=3,cw=[(1,70),(2,35),(3,35)] )

    pm.radioButtonGrp('directionOption', label='+ or -', labelArray2=['+', '-'], numberOfRadioButtons=2,cw=[(1,70),(2,35)] )
    
    pm.button(l='Align Joints (select joints in chain you want to align)', c=alignChain, w=190, h=40, bgc=[0.2, 0.2, 0.2])

    pm.separator(style='none', h=20)

    pm.button(l='Finalize Rig',c=finalize, w=190,h=40,bgc=[0.2,0.2,0.2])

    pm.separator(style = 'none', h=20)


    pm.button(l='Exit',c=partial(quit,"AutoRig_JT"), w=190,h=40,bgc=[0.2,0.2,0.2])	

    print windowUI

    pm.showWindow(windowUI)
	
    pm.window("AutoRig_JT", e=True,w=300,h=600)
Пример #42
0
def cgFxShaderSetup(files):

    shdPath = str( pm.internalVar( uad = True ) + "scripts/pipeline/shaders/")

    getSel = pm.ls(selection = True)

    shdName = str(getSel[0]+"_CGFX")

    cgfx = pm.shadingNode("cgfxShader", asShader = True, n = shdName)
    pm.mel.eval('cgfxShader -e -fx  "'+shdPath+'cgfx/lcUberShader_3.0.cgfx" '+shdName+";")

    # create file nodes for all textures and set them up
    # setup diffuse
    difNode = tx.texNode(cgfx, "Diffuse", getSel[0])
    if not files['Diffuse'] == "":
        print "setting file: "+str(files['Diffuse'])
        print "to Diffuse Channel"
        pm.setAttr(difNode+".fileTextureName", str(files['Diffuse']))
    pm.setAttr(str(shdName+".useDiffuseMap"), True)
    # now connect our new file node to the shader
    difNode.outColor >> cgfx.diffuseMapSampler

    # setup specular
    specNode = tx.texNode(cgfx, "Specular", getSel[0])
    if not files['Specular'] == "":
        print "setting file: "+str(files['Specular'])
        print "to Specular Channel"
        pm.setAttr(specNode+".fileTextureName", str(files['Specular']))
    pm.setAttr(str(shdName+".useSpecularMap"), True)
    # now connect our new file node to the shader
    specNode.outColor >> cgfx.specularMapSampler

    # setup normal
    nrmlNode = tx.texNode(cgfx, "Normal", getSel[0])
    if not files['Normal'] == "":
        print "setting file: "+str(files['Normal'])
        print "to Normal Channel"
        pm.setAttr(nrmlNode+".fileTextureName", str(files['Normal']))
    pm.setAttr(str(shdName+".useNormalMap"), True)
    # now connect our new file node to the shader
    nrmlNode.outColor >> cgfx.normalMapSampler


    # I should check to see if this node exists before I just set it up
    envNode = tx.texNode(cgfx, "Environment", "cgfx")
    pm.setAttr("cgfxEnvironment_File.fileTextureName", str(shdPath+"CubeMaps/sunsetCube.dds"))
    envNode.outColor >> cgfx.envCubeMapSampler

    pm.setAttr(str(shdName+".useReflCube"), True)
    pm.setAttr(str(shdName+".useAmbCube"), True)
    # create a three point light setup
    lights = ld.threePointlight("directional")
    # connecting the lights to the shader
    pm.mel.eval("cgfxShader_connectVector "+shdName+".light1Dir "+lights[0]+";")
    pm.setAttr(str(shdName+".light1Color"),[1.0, 0.95, 0.82])
    pm.mel.eval("cgfxShader_connectVector "+shdName+".light2Dir "+lights[1]+";")
    pm.setAttr(str(shdName+".light2Color"),[0.61, 0.8, 1.0])
    pm.mel.eval("cgfxShader_connectVector "+shdName+".light3Dir "+lights[2]+";")
    pm.setAttr(str(shdName+".light3Color"),[0.4, 0.4, 0.4])

    # assign Material
    # create a surface Shader and attach out cgfx shader to it.
    cgfxShd = pm.sets(renderable=True, noSurfaceShader=True, empty=True, name=str(shdName+"SurfaceShader"))
    cgfx.outColor >> cgfxShd.surfaceShader
    # Assign the Shader to the objects
    pm.sets(cgfxShd, edit=True, forceElement=getSel[0])
    pm.select(clear=True)
    pm.select(cgfx)