Example #1
0
    def _add_context_menu(self):
        """
        Adds a context menu which displays the current context
        """

        ctx = self._engine.context
        ctx_name = str(ctx)

        # create the menu object
        # the label expects a unicode object so we cast it to support when the context may
        # contain info with non-ascii characters
        ctx_menu = pm.subMenuItem(label=ctx_name.decode("utf-8"),
                                  parent=self._menu_handle)

        # link to UI
        pm.menuItem(label="Jump to Shotgun",
                    parent=ctx_menu,
                    command=Callback(self._jump_to_sg))

        # Add the menu item only when there are some file system locations.
        if ctx.filesystem_locations:
            pm.menuItem(label="Jump to File System",
                        parent=ctx_menu,
                        command=Callback(self._jump_to_fs))

        # divider (apps may register entries below this divider)
        pm.menuItem(divider=True, parent=ctx_menu)

        return ctx_menu
Example #2
0
    def __init__(self):
        global offsetCurveOptions

        with pdil.ui.singleWindow(self.id):
            with columnLayout():
                self.mode = radioButtonGrp(
                    nrb=3,
                    la3=['Playback Range', 'User Defined', 'All'],
                    on1=Callback(self.setPlaybackMode),
                    on2=Callback(self.setUserMode),
                    on3=Callback(self.setAllMode),
                )

                with rowColumnLayout(nc=2) as self.range:
                    self.start = intField()
                    self.end = intField()

                with rowColumnLayout(nc=2):
                    #checkBox(l='Autokey', en=False)
                    button(label='Apply', c=Callback(self.apply))

            if offsetCurveOptions.uiMode == 1:
                self.setPlaybackMode()
            elif offsetCurveOptions.uiMode == 2:
                self.setUserMode()
            elif offsetCurveOptions.uiMode == 3:
                self.setAllMode()
Example #3
0
    def __init__(self):
        columnLayout()
        button(l="Match Selected Orients", c=Callback(matchOrient), w=200)
        button(l="Custom Up", c=Callback(customUp), w=200)

        rowLayout(nc=2)
        button(l="Hide Orients", w=200, c=Callback(hideOrients))
        button(l="Show Orients", w=200, c=Callback(showOrients))
        setParent("..")

        rowLayout(nc=2)
        button(l="Hide Connectors",
               w=200,
               c=Callback(connectorDisplayToggle, False))
        button(l="Show Connectors",
               w=200,
               c=Callback(connectorDisplayToggle, True))
        setParent("..")

        rowLayout(nc=2)
        button(l="Hide Handles", w=200, c=Callback(handleDisplayToggle, False))
        button(l="Show Handles", w=200, c=Callback(handleDisplayToggle, True))
        setParent("..")

        button(l="Reconnect Real Bones",
               w=200,
               c=Callback(fossil_card.reconnectRealBones))
        button(l="Ensure Cards have Output Attrs", w=200)
Example #4
0
def mantraMainMenu():
    log.debug("Creating mantra main menu")
    menuName = "Mantra"
    if pm.menu(menuName, query=True, exists=True):
        pm.deleteUI(menuName)
    gMainWindow = pm.mel.eval('$tmpVar=$gMainWindow')
    mantraMenu = pm.menu(menuName, label = menuName, parent = gMainWindow, tearOff = True )
    pm.menuItem( label = 'AttributeManager', command = Callback(menuCallback, "AttributeManager") )
    pm.menuItem( label = 'DummyMenu' , command = Callback(menuCallback, "Dummy") )
    pm.menuItem( label = '', divider = True )
    pm.menuItem( label = 'DummyMenuA' , command = Callback(menuCallback, "DummyA") )
    pm.setParent("..", menu = True)
Example #5
0
    def __init__(self, ui):

        self.ui = ui

        self.update()

        self.ui.visGroups.itemSelectionChanged.connect(
            Callback(self.selectGroup))

        self.ui.equipVisControl.clicked.connect(Callback(self.equip))
        self.ui.unequipVisControl.clicked.connect(Callback(self.unequip))
        self.ui.pruneVisGroups.clicked.connect(Callback(self.prune))

        self.ui.assignVisGroup.clicked.connect(Callback(self.assign))
Example #6
0
    def __init__(self):
        with pdil.ui.singleWindow('BoneGroups'):
            columnLayout()
            self.lister = textScrollList(dcc=Callback(self.select),
                                         sc=Callback(self.setName))

            groupNames = set()
            for card in find.blueprintCards():
                boneGroups = card.rigData.get('boneGroups', {})
                groupNames.update(boneGroups.keys())

            self.lister.append(sorted(groupNames))

            button(l='Add To group', c=Callback(self.addToGroup))
            self.name = textField()
Example #7
0
    def __init__(self, settingsObj):
        rowColumnLayout(nc=2)

        # LegType UI
        text(l='Leg Type')
        self.legType = optionMenu(l='')
        menuItem(l='Human')
        menuItem(l='Dogleg')
        settingsObj.settings.optionMenuSetup(self.legType, 'legType')

        # Spine Orient UI
        text(l="Spine Orientation")
        self.spineOrient = optionMenu(l='')
        menuItem('Vertical')
        menuItem('Horizontal')
        settingsObj.settings.optionMenuSetup(self.spineOrient, 'spineOrient')

        text(l='Number of Spine Joints')
        self.spineCount = intFieldGrp(nf=1, v1=settingsObj.settings.spineCount)
        text(l='Number of Fingers')
        self.fingerCount = intFieldGrp(nf=1,
                                       v1=settingsObj.settings.fingerCount)
        text(l="Thumb")
        self.thumb = checkBox(l='', v=settingsObj.settings.thumb)

        #setParent("..")

        text(l='')
        text(l='')
        text(l='')
        button(l="Start", w=300, c=Callback(self.start))
Example #8
0
    def buildShapeMenu(self):

        shapeFolder = os.path.dirname(__file__).replace('\\', '/') + '/shapes'

        shapeNames = controllerShape.listShapes()

        temp_style = []
        template = "QPushButton#%s { background-image: url('%s'); border: none; }"  # padding: 0; margin: 0;
        for name in shapeNames:
            temp_style.append(template %
                              (name, shapeFolder + '/' + name + '.png'))

        self.window.setStyleSheet('\n'.join(temp_style))

        row = 0
        col = 0

        for f in os.listdir(shapeFolder):
            if f.lower().endswith('.png'):
                shapeName = f[:-4]
                if shapeName in shapeNames:
                    button = Qt.QtWidgets.QPushButton()
                    button.setFixedSize(64, 64)

                    button.setObjectName(f[:-4])

                    button.clicked.connect(
                        Callback(self.changeShape, shapeName))

                    self.shape_chooser.addWidget(button, row, col)

                    col += 1
                    if col >= self.NUM_COLS:
                        col = 0
                        row += 1
Example #9
0
 def __init__(self):
     with columnLayout() as self.main:
         button(l='Select CVs', c=core.alt.Callback(self.selectCVs))
         button(l='Select Pin Head', c=Callback(self.selectPinHead))
         text(l='')
         button(l='Rotate X 45', c=core.alt.Callback(self.rotate, 'x', 45))
         button(l='Rotate Y 45', c=core.alt.Callback(self.rotate, 'y', 45))
         button(l='Rotate Z 45', c=core.alt.Callback(self.rotate, 'z', 45))
         text(l='')
Example #10
0
    def __init__(self):
        frameLayout(l='Visiblity Groups')

        columnLayout()
        text(l='Existing Groups')
        self.current = textScrollList(nr=10,
                                      sc=core.alt.Callback(self.selectGroup))
        self.groupName = textFieldButtonGrp(l="Assign to Group", bl='Assign')
        text(l='')
        button(l='Use Vis Shared Shape', c=Callback(self.use))
        text(l='')
        button(l='Remove Vis Shared Shape', c=Callback(self.remove))
        text(l='')
        button(l='Prune Unused Vis Groups', c=Callback(self.prune))
        setParent("..")

        setParent("..")

        self.update()
Example #11
0
    def nameRulesWindow(self):

        win = window(
            t='Choose what is displayed to indicate the side of the joints and controllers.'
        )
        with columnLayout(adj=True):
            jl = textFieldGrp(l='Joint Left Side',
                              tx=self.settings['joint_left'])
            jr = textFieldGrp(l='Joint Right Side',
                              tx=self.settings['joint_right'])

            cl = textFieldGrp(l='Control Left Side',
                              tx=self.settings['control_left'])
            cr = textFieldGrp(l='Control Right Side',
                              tx=self.settings['control_right'])

            def setSides():
                jlText = jl.getText().strip()
                jrText = jr.getText().strip()

                clText = cl.getText().strip()
                crText = cr.getText().strip()

                if jlText == jrText or clText == crText:
                    confirmDialog(
                        m='The left and right sides must be different\n(but the control and joint text for the same side can be the same)'
                    )
                    return

                if not clText or not crText or not jlText or not jrText:
                    confirmDialog(m='You cannot leave any side empty.')
                    return

                self.settings['joint_left'] = jlText
                self.settings['joint_right'] = jrText

                self.settings['control_left'] = clText
                self.settings['control_right'] = crText

                settings.JOINT_SIDE_CODE_MAP['left'] = jlText
                settings.JOINT_SIDE_CODE_MAP['right'] = jrText

                settings.CONTROL_SIDE_CODE_MAP['left'] = clText
                settings.CONTROL_SIDE_CODE_MAP['right'] = crText

                deleteUI(win)

            button(l='Apply', c=Callback(setSides))

        showWindow()
Example #12
0
    def buildShapeMenu(self, scale):

        shapeFolder = os.path.dirname(__file__).replace('\\', '/') + '/shapes'

        shapeNames = controllerShape.listShapes()
        """
        Old way had transparent background, but didn't scale the icons if the monitor had a scale set.  New version
        does at the sacrifice of transparent background
        
        temp_style = []
        template = "QPushButton#%s { background-image: url('%s'); border: none; width: 90; height: 90;}"  # padding: 0; margin: 0;
        for name in shapeNames:
            temp_style.append( template % (name, shapeFolder + '/' + name + '.png') )
        
        self.window.setStyleSheet( '\n'.join(temp_style) )
        """
        row = 0
        col = 0

        for f in os.listdir(shapeFolder):
            if f.lower().endswith('.png'):
                shapeName = f[:-4]
                if shapeName in shapeNames:
                    button = Qt.QtWidgets.QPushButton()
                    button.setFixedSize(64 * scale, 64 * scale)

                    #button.setObjectName(f[:-4])

                    img = PySide2.QtGui.QPixmap(shapeFolder + '/' + f)
                    img = img.scaled(
                        PySide2.QtCore.QSize(64 * scale, 64 * scale),
                        PySide2.QtCore.Qt.AspectRatioMode.IgnoreAspectRatio,
                        PySide2.QtCore.Qt.TransformationMode.
                        SmoothTransformation)

                    button.setFlat(True)
                    button.setAutoFillBackground(True)

                    button.setIcon(img)
                    button.setIconSize(img.size())

                    button.clicked.connect(
                        Callback(self.changeShape, shapeName))

                    self.shape_chooser.addWidget(button, row, col)

                    col += 1
                    if col >= self.NUM_COLS:
                        col = 0
                        row += 1
Example #13
0
    def _add_context_menu(self):
        """
        Adds a context menu which displays the current context
        """        
        
        ctx = self._engine.context
        ctx_name = str(ctx)        
        
        # create the menu object
        ctx_menu = pm.subMenuItem(label=ctx_name, parent=self._menu_handle)
        
        # link to UI
        pm.menuItem(label="Jump to Shotgun", 
                    parent=ctx_menu, 
                    command=Callback(self._jump_to_sg))
        pm.menuItem(label="Jump to File System", 
                    parent=ctx_menu, 
                    command=Callback(self._jump_to_fs))


        # divider (apps may register entries below this divider)
        pm.menuItem(divider=True, parent=ctx_menu)
        
        return ctx_menu
Example #14
0
 def listAdjustments(self):
     self.ui.aligns.blockSignals(True)
     
     self.ui.aligns.clearContents()
     
     cards = find.blueprintCards()
     
     self.commands = []
     unused = []
     for card in cards:
         with card.rigData as data:
             if 'tpose' in data:
                 for alignCmd in data['tpose']:
                     self.commands.append( Adjust(alignCmd['order'], card, alignCmd) )
                 
             else:
                 unused.append( card )
     
     self.ui.aligns.setRowCount( len(self.commands) )
     
     self.commands.sort()
     
     for row, (order, card, data) in enumerate(self.commands):
         self.ui.aligns.setItem(row, 0, self.TWItem(card.name()))
         #self.ui.aligns.setItem(row, 1, self.TWItem(str(order), readOnly=False))
         button = Qt.QtWidgets.QPushButton(str(order))
         button.clicked.connect( Callback(self.moveItem, order) )
         self.ui.aligns.setCellWidget(row, 1, button)
         self.ui.aligns.setItem(row, 2, self.TWItem(data['call']))
         self.ui.aligns.setItem(row, 3, self.TWItem(str(data['args']), readOnly=False))
     
     self.ui.aligns.blockSignals(False)
     
     
     self.cardNames = OrderedDict( sorted([(c.name(), c) for c in find.blueprintCards()]) )
     self.ui.cardChooser.addItems( self.cardNames.keys() )
     '''
Example #15
0
    def add_command_to_menu(self, menu):
        """
        Adds an app command to the menu
        """

        # create menu sub-tree if need to:
        # Support menu items seperated by '/'
        parent_menu = menu
        parts = self.name.split("/")
        for item_label in parts[:-1]:

            # see if there is already a sub-menu item
            sub_menu = self._find_sub_menu_item(parent_menu, item_label)
            if sub_menu:
                # already have sub menu
                parent_menu = sub_menu
            else:
                # create new sub menu
                params = {
                    "label": item_label,
                    "parent": parent_menu,
                    "subMenu": True
                }
                parent_menu = pm.menuItem(**params)

        # finally create the command menu item:
        params = {
            "label": parts[-1],  #self.name,
            "command": Callback(self._execute_deferred),
            "parent": parent_menu,
        }
        if "tooltip" in self.properties:
            params["annotation"] = self.properties["tooltip"]
        if "enable_callback" in self.properties:
            params["enable"] = self.properties["enable_callback"]()

        pm.menuItem(**params)
Example #16
0
def nameRulesWindow():

    with pdil.ui.singleWindow(
            'nameRulesWindow',
            t='Choose what is displayed to indicate the side of the joints and controllers.'
    ) as win:
        with columnLayout(adj=True):
            jl = textFieldGrp('jointLeft',
                              l='Joint Left Side',
                              tx=config._settings['joint_left'])
            jr = textFieldGrp('jointRight',
                              l='Joint Right Side',
                              tx=config._settings['joint_right'])

            cl = textFieldGrp('controlLeft',
                              l='Control Left Side',
                              tx=config._settings['control_left'])
            cr = textFieldGrp('controlRight',
                              l='Control Right Side',
                              tx=config._settings['control_right'])

            root = textFieldGrp('root',
                                l='Root Joint Name',
                                tx=config._settings['root_name'])
            prefixField = textFieldGrp('jointPrefix',
                                       l='Joint Prefix',
                                       tx=config._settings['joint_prefix'])

            def setNames():
                jlText = jl.getText().strip()
                jrText = jr.getText().strip()

                clText = cl.getText().strip()
                crText = cr.getText().strip()

                rootName = root.getText().strip()

                if jlText == jrText or clText == crText:
                    pdil.ui.notify(
                        m='The left and right sides must be different\n(but the control and joint text for the same side can be the same)'
                    )
                    return

                if not clText or not crText or not jlText or not jrText or not rootName:
                    pdil.ui.notify(
                        m='You cannot leave any side empty and root must have a name'
                    )
                    return

                config._settings['joint_left'] = jlText
                config._settings['joint_right'] = jrText

                config._settings['control_left'] = clText
                config._settings['control_right'] = crText

                config.JOINT_SIDE_CODE_MAP['left'] = jlText
                config.JOINT_SIDE_CODE_MAP['right'] = jrText

                config.CONTROL_SIDE_CODE_MAP['left'] = clText
                config.CONTROL_SIDE_CODE_MAP['right'] = crText

                config._settings['root_name'] = rootName
                config._settings['joint_prefix'] = prefixField.getText().strip(
                )

                deleteUI(win)

            button(l='Apply', c=Callback(setNames))

    return win, setNames
Example #17
0
    def __init__(self, *args, **kwargs):

        self.settings = pdil.ui.Settings(
            'Fossil GUI Settings',
            {
                'spineCount': 5,
                'fingerCount': 4,
                'thumb': True,
                'spineOrient': 'Vertical',
                'legType': 'Human',
                'currentTabIndex':
                1,  # 1-base AFAIK THE ONLY ONE ACTUALLY NEEDED
                'panels': [75, 75, 25, 100, 75, 25],
                'rebuildMode': 'Use Current Shapes',
                'closedControlFrame': False,
                'closeDebugFrame': True,
                'showIndividualRestore': False,
                'showRigStateDebug': False,
                'runUpdaters': True,
            })

        objectName = 'Rig_Tool'
        # Remove any existing windows first
        pdil.ui.deleteByName(objectName)

        super(RigTool, self).__init__(pdil.ui.mayaMainWindow())

        # Not sure how else to get window's scale factor for high dpi displays
        self.scaleFactor = self.font().pixelSize() / 11.0

        self.ui = RigToolUI()
        self.ui.setupUi(self)

        self.setObjectName(objectName)
        self.setWindowTitle('Fossil')

        # Menu callbacks
        self.ui.actionReconnect_Real_Joints.triggered.connect(
            Callback(fossil_card.reconnectRealBones))
        self.ui.actionMatch_Selected_Orients.triggered.connect(
            Callback(matchOrient))

        self.ui.actionCard_Orients_2.triggered.connect(
            Callback(self.orientsToggle))

        # &&& I think this isn't useful but I'm going to wait a while to be sure.
        #self.ui.actionConnectors.triggered.connect( Callback(self.connectorDisplayToggle) )
        self.ui.menuVisibility.removeAction(self.ui.actionConnectors)

        self.ui.actionHandles.triggered.connect(
            Callback(self.handleDisplayToggle))

        self.ui.actionNaming_Rules.triggered.connect(Callback(nameRulesWindow))

        self.ui.actionShow_Individual_Restores.setChecked(
            self.settings['showIndividualRestore'])
        self.ui.actionShow_Card_Rig_State.setChecked(
            self.settings['showRigStateDebug'])

        self.ui.actionShow_Individual_Restores.triggered.connect(
            Callback(self.restoreToggle))
        self.ui.actionShow_Card_Rig_State.triggered.connect(
            Callback(self.rigStateToggle))

        # Callback setup

        self.ui.makeCardBtn.clicked.connect(self.makeCard)
        self.ui.selectAllBtn.clicked.connect(self.selectAll)
        self.ui.buildBonesBtn.clicked.connect(Callback(fossil_card.buildBones))
        self.ui.deleteBonesBtn.clicked.connect(
            Callback(fossil_card.deleteBones))
        self.ui.buildRigBtn.clicked.connect(fossil_card.buildRig)
        self.ui.deleteRigBtn.clicked.connect(
            partial(util.runOnEach, operator.methodcaller('removeRig'),
                    'Delting Rig'))
        self.ui.saveModsBtn.clicked.connect(
            partial(util.runOnEach, operator.methodcaller('saveState'),
                    'Saving State'))
        self.ui.restoreModsBtn.clicked.connect(
            partial(util.runOnEach, operator.methodcaller('restoreState'),
                    'Restoring State'))

        self.ui.duplicateCardBtn.clicked.connect(self.duplicateCard)
        self.ui.mergeCardBtn.clicked.connect(self.mergeCard)
        self.ui.splitCardBtn.clicked.connect(self.splitCard)

        self.ui.addCardIkButton.clicked.connect(Callback(self.addCardIk))
        self.ui.remCardIkButton.clicked.connect(Callback(self.removeCardIk))

        self.ui.insertJointBtn.clicked.connect(self.insertJoint)
        self.ui.addTipBtn.clicked.connect(partial(self.insertJoint, True))
        self.ui.deleteJointBtn.clicked.connect(self.deleteJoint)

        self.ui.rebuildProxyBtn.clicked.connect(
            proxyskel.rebuildConnectorProxy)

        self.ui.customUpBtn.clicked.connect(Callback(customUp))

        self.ui.updateRigState.clicked.connect(self.updateField)

        self.ui.space_save.clicked.connect(
            partial(self.targeted_save, 'spaces'))
        self.ui.space_load.clicked.connect(
            partial(self.targeted_load, 'spaces'))
        self.ui.vis_save.clicked.connect(
            partial(self.targeted_save, 'visGroup'))
        self.ui.vis_load.clicked.connect(
            partial(self.targeted_load, 'visGroup'))
        self.ui.shape_save.clicked.connect(partial(self.targeted_save,
                                                   'shape'))
        self.ui.shape_local_load.clicked.connect(
            partial(self.targeted_load, 'shape_local'))
        self.ui.shape_world_load.clicked.connect(
            partial(self.targeted_load, 'shape_world'))
        self.ui.constraints_save.clicked.connect(
            partial(self.targeted_save, 'constraints'))
        self.ui.constraints_load.clicked.connect(
            partial(self.targeted_load, 'constraints'))
        self.ui.connections_save.clicked.connect(
            partial(self.targeted_save, 'connections'))
        self.ui.connections_load.clicked.connect(
            partial(self.targeted_load, 'connections'))
        self.ui.driven_save.clicked.connect(
            partial(self.targeted_save, 'setDriven'))
        self.ui.driven_load.clicked.connect(
            partial(self.targeted_load, 'setDriven'))
        self.ui.custom_save.clicked.connect(
            partial(self.targeted_save, 'customAttrs'))
        self.ui.custom_load.clicked.connect(
            partial(self.targeted_load, 'customAttrs'))
        self.ui.locked_save.clicked.connect(
            partial(self.targeted_save, 'lockedAttrs'))
        self.ui.locked_load.clicked.connect(
            partial(self.targeted_load, 'lockedAttrs'))

        def restore(key, restoreFunc):
            print('Restoring', key)
            [
                c._restoreData(restoreFunc, c.rigState[key])
                for c in util.selectedCards()
            ]

        # Individual restore commands
        for niceName, (harvestFunc,
                       restoreFunc) in nodeApi.Card.toSave.items():
            button = getattr(self.ui, niceName + 'Restore')
            button.clicked.connect(partial(restore, niceName, restoreFunc))
        '''
        self.restoreShapes(objectSpace=shapesInObjectSpace)
        '''

        # Start Group Tab
        self.startTabLayout = Qt.QtWidgets.QVBoxLayout(self.ui.tab)
        self.startTabLayout.setObjectName(self.FOSSIL_START_TAB)
        setParent(self.FOSSIL_START_TAB)
        self.startTab = startingTab.StartLayout(self)

        # Vis Group Tab
        self.visGroupProxy = _visGroup.VisGroupLayout(self.ui)

        # Space Tab
        self.spaceTab = spacesTab.SpaceTab(self.ui)

        # Card Lister setup
        self.updateId = scriptJob(e=('SelectionChanged',
                                     pdil.alt.Callback(self.selectionChanged)))
        self.ui.cardLister.setup(self.scaleFactor)

        self.ui.cardLister.itemSelectionChanged.connect(
            self.cardListerSelection)

        self.ui.cardLister.cardListerRefresh(force=True)
        self.ui.cardLister.updateHighlight()

        self.ui.jointLister.setup(self.scaleFactor)

        self.ui.cardLister.namesChanged.connect(
            self.ui.jointLister.jointListerRefresh)

        self.ui.restoreContainer.setVisible(
            self.settings['showIndividualRestore'])
        self.ui.rigStateContainer.setVisible(
            self.settings['showRigStateDebug'])

        pdil.pubsub.subscribe('fossil rig type changed', self.forceCardParams)

        # Controller Edit
        self.shapeEditor = controllerEdit.ShapeEditor(self)

        #-
        self.show()

        pdil.pubsub.subscribe(pdil.pubsub.Event.MAYA_DAG_OBJECT_CREATED,
                              self.ui.cardLister.newObjMade)

        self.uiActive = True
        self._uiActiveStack = []

        self.ui.tabWidget.setCurrentIndex(self.settings['currentTabIndex'])

        if 'geometry' in self.settings:
            pdil.ui.setGeometry(self, self.settings['geometry'])

        pdil.pubsub.publish('fossil rig type changed')
        selectedCard = util.selectedCardsSoft(single=True)
        self.ui.jointLister.jointListerRefresh(selectedCard)
        self.ui.jointLister.refreshHighlight()

        if self.settings['runUpdaters']:
            self.runUpdatersId = scriptJob(e=('SceneOpened', updater.checkAll))
            updater.checkAll()
Example #18
0
    def createUi(self, node=None):
        log.debug("createUi for node %s" % str(node))
        currentSegment = ""
        layoutList = []
        for att in self.attList:
            if att.kategory != None and currentSegment != att.kategory:
                log.debug("kategory %s != %s" % (currentSegment, att.kategory))
                katlist = att.kategory.split("|")
                diff = len(layoutList) - len(katlist)
                # neue liste ist kuerzer als alte, also solange dicht machen bis die laenge gleich ist
                log.debug("check diff %d" % diff)
                while diff > 0:
                    layoutList.pop()
                    pm.setParent("..")
                    pm.setParent("..")
                    diff = len(layoutList) - len(katlist)
                    log.debug("new diff %d" % diff)

                # alte liste ist nun nicht laenger als neue liste
                # durchgehen und alles dichtmachen was nicht gleich ist
                for i in range(len(layoutList)):
                    kat = katlist[i]
                    ckat = layoutList[i]
                    # wenn werte ungelich dann alles was noch kommt zumachen
                    if kat != ckat:
                        laylen = len(layoutList)
                        for n in range(i, laylen):
                            pm.setParent("..")
                            pm.setParent("..")
                            layoutList.pop(n)

                # nun sollte sichergestellt sein, dass layoutList nur noch elemente
                # enthaelt, die gleich sind, also kann man daran anknuepfen
                for i in range(len(layoutList), len(katlist)):
                    log.debug("opening layout for katlist %s %d %s" %
                              (str(katlist), i, katlist[i]))
                    self.beginUISegment(katlist[i])
                    layoutList.append(katlist[i])

                currentSegment = att.kategory

            if MAP_API_ATTR.has_key(att.type):
                log.debug("Adding element %s with displayName %s" %
                          (att.attname, att.displayname))
                attype, attypeval = MAP_API_ATTR[att.type]
                log.debug(
                    "Adding attribute named %s type %s val %s default %s" %
                    (att.attname, attype, attypeval, att.default))
                if attypeval == 'bool':
                    att.uiElement = pm.checkBoxGrp(att.attname,
                                                   numberOfCheckBoxes=1,
                                                   label1=att.displayname,
                                                   cc=Callback(
                                                       self.dimConnections,
                                                       att))
                    att.uiDimFunction = pm.checkBoxGrp
                    if node:
                        pm.connectControl(att.uiElement,
                                          node + "." + att.attname,
                                          index=2)
                if attypeval == 'int':
                    att.uiElement = pm.intFieldGrp(att.attname,
                                                   numberOfFields=1,
                                                   label=att.displayname,
                                                   value1=att.default,
                                                   cc=Callback(
                                                       self.dimConnections,
                                                       att))
                    att.uiDimFunction = pm.intFieldGrp
                    if node:
                        pm.connectControl(att.uiElement,
                                          node + "." + att.attname,
                                          index=2)
                if attypeval == 'long2':
                    if node:
                        att.uiDimFunction = pm.attrFieldGrp(
                            attribute='%s' % (node + "." + att.attname),
                            cc=Callback(self.dimConnections, att))
                if attypeval == 'float':
                    att.uiElement = pm.floatFieldGrp(att.attname,
                                                     numberOfFields=1,
                                                     label=att.displayname,
                                                     value1=att.default,
                                                     cc=Callback(
                                                         self.dimConnections,
                                                         att))
                    att.uiDimFunction = pm.floatFieldGrp
                    if node:
                        pm.connectControl(att.uiElement,
                                          node + "." + att.attname,
                                          index=2)
                if attypeval == 'float2':
                    if node:
                        att.uiDimFunction = pm.attrFieldGrp(
                            attribute='%s' % (node + "." + att.attname),
                            cc=Callback(self.dimConnections, att))
                if attypeval == 'string':
                    att.uiElement = pm.textFieldGrp(att.attname,
                                                    label=att.displayname,
                                                    text=att.default,
                                                    cc=Callback(
                                                        self.dimConnections,
                                                        att))
                    pm.connectControl(att.uiElement,
                                      node + "." + att.attname,
                                      index=2)
                    pm.textFieldGrp(att.uiElement, edit=True, text=att.default)

                if attypeval == 'enum':
                    poplist = map(list, enumerate(att.values))

                    if node:
                        nodeatt = node + "." + att.attname
                        att.uiElement = pm.attrEnumOptionMenuGrp(
                            att.attname,
                            label=att.displayname,
                            at=nodeatt,
                            ei=poplist,
                            vcc=Callback(self.dimConnections, att))
                        att.uiDimFunction = pm.attrEnumOptionMenuGrp
                    else:
                        att.uiElement = pm.attrEnumOptionMenuGrp(
                            att.attname,
                            label=att.displayname,
                            ei=poplist,
                            vcc=Callback(self.dimConnections, att))
                        att.uiDimFunction = pm.attrEnumOptionMenuGrp

                if attypeval == 'message':
                    pass

        if len(layoutList) > 0:
            for i in range(len(layoutList)):
                pm.setParent("..")
                pm.setParent("..")
Example #19
0
def animationSwitchMenu(objName):
    '''
    Called from dagMenuProc() so it's wrapped to catch any error.
    '''

    try:
        obj = PyNode(objName)
        
        plug = controllerShape.getSwitcherPlug(obj)
        
        spaces = space.getNames(obj)
        
        #-------
        # Mode
        #-------
        if plug or spaces:
            
            def setMode(mode):
                animToolSettings.switchMode = mode

            menuItem(l='Mode: Current Frame',  c=Callback(setMode, 'current'), cb=eq(animToolSettings.switchMode, 'current') )  # noqa e241
            menuItem(l='Mode: Playback Range', c=Callback(setMode, 'range'), cb=eq(animToolSettings.switchMode, 'range') )  # noqa e241
            menuItem(l='Mode: All',            c=Callback(setMode, 'all'), cb=eq(animToolSettings.switchMode, 'all') )  # noqa e241
            
        #-------
        # Ik/Fk
        #-------
        if plug:
            if cmds.getAttr(obj + '.fossilCtrlType') in ['translate', 'rotate']:
                destType = 'Ik'
            else:
                destType = 'Fk'
                
            if core.time.rangeIsSelected():
                s, e = core.time.selectedTime()
            elif animToolSettings.switchMode == 'current':
                s, e = [currentTime(q=1)] * 2
            elif animToolSettings.switchMode == 'range':
                s, e = core.time.playbackRange()
            elif animToolSettings.switchMode == 'all':
                s, e = None, None
            
            '''
            The dag menu can be triggered:
            * Object is selected but right click is on nothing
            * Object is selected but right click is on another object
            * Nothing is selected right clicking over an object
            
            Therefore it's a bunch of work to figure out if several things should be considered or not.
            '''
            sel = selected()
            if len(sel) <= 1 and (sel[0] == obj if sel else True):
                menuItem(l='Switch to ' + destType, c=core.alt.Callback(kinematicSwitch.ikFkSwitch, obj, s, e))
                
            else:
                sel = set(sel)
                sel.add(obj)
                
                switches = {}
                
                for o in sel:
                    switchPlug = controllerShape.getSwitcherPlug(o)
                    switches[ switchPlug.rsplit('|')[-1] ] = o
                
                if len(switches) == 1:
                    menuItem(l='Switch to ' + destType, c=core.alt.Callback(kinematicSwitch.ikFkSwitch, obj, s, e))
                else:
                    menuItem(l='Switch mutliple', c=core.alt.Callback(kinematicSwitch.multiSwitch, switches.values(), s, e))
            
        #-------
        # Spaces
        #-------
        if spaces:
            objsToSwitch = [obj]
            # Check if other selected objects have spaces to possibly swich to.
            sel = selected()
            if obj not in sel:
                sel.append(obj)
            
            if len(sel) > 1:
                allSpaces = []
                for o in sel:
                    tempSpaces = space.getNames(o)
                    if tempSpaces:
                        allSpaces.append(tempSpaces)
                        
                if len(allSpaces) > 1:
                    objsToSwitch = sel
                    spaces = set(allSpaces[0]).intersection( allSpaces[1] )
                    
                    for t in allSpaces[2:]:
                        spaces.intersection_update(t)
                        
            if spaces:
                menuItem(l='Switch space from %s to' % obj.space.get(asString=True), sm=True)
                for _space in sorted(spaces):
                    menuItem(l=_space, c=Callback(switchSpaceGroup, objsToSwitch, _space))
                setParent('..', m=True)
        
        #-------
        # Main
        #-------
        """
        if lib.dagObj.simpleName(obj) == 'main':
            isMain = True
            if objExists(CONSTRAINT_SET_NAME):
                if PyNode(CONSTRAINT_SET_NAME).elements():
                    menuItem(l='Main Control Re-Lock', c=Callback(relockMain))
                else:
                    menuItem(l='Main Control Unlock', c=Callback(unlockMain))
            else:
                menuItem(l='Main Control Unlock', c=Callback(unlockMain))
                
            menuItem(l='Main Zero', sm=True)
            menuItem(l='All')
            for attr in [trans + axis for trans in 'tr' for axis in 'xyz']:
                skip = [trans + axis for trans in 'tr' for axis in 'xyz']
                skip.remove(attr)
                menuItem(l='Zero ' + attr, c=Callback(resetMain, skip))
            setParent('..', m=True)
                
        else:
            isMain = False
        
        # Divider, if needed
        """
        if plug or spaces:
            menuItem(d=True)
            
    except Exception:
        print( traceback.format_exc() )
Example #20
0
def animationSwitchMenu(objName):
    '''
    Called from dagMenuProc() so it's wrapped to catch any error.
    '''

    try:
        obj = PyNode(objName)

        plug = controller.getSwitcherPlug(obj)

        spaces = space.getNames(obj)

        #-------
        # Mode
        #-------
        if plug or spaces:

            def setMode(mode):
                animToolSettings.switchMode = mode

            menuItem(l='Mode: Current Frame',
                     c=Callback(setMode, 'current'),
                     cb=eq(animToolSettings.switchMode,
                           'current'))  # noqa e241
            menuItem(l='Mode: Playback Range',
                     c=Callback(setMode, 'range'),
                     cb=eq(animToolSettings.switchMode, 'range'))  # noqa e241
            menuItem(l='Mode: All',
                     c=Callback(setMode, 'all'),
                     cb=eq(animToolSettings.switchMode, 'all'))  # noqa e241

        #-------
        # Ik/Fk
        #-------
        if plug:
            if cmds.getAttr(obj +
                            '.motigaCtrlType') in ['translate', 'rotate']:
                destType = 'Ik'
            else:
                destType = 'Fk'

            if core.time.rangeIsSelected():
                s, e = core.time.selectedTime()
            elif animToolSettings.switchMode == 'current':
                s, e = [currentTime(q=1)] * 2
            elif animToolSettings.switchMode == 'range':
                s, e = core.time.playbackRange()
            elif animToolSettings.switchMode == 'all':
                s, e = None, None

            menuItem(l='Switch to ' + destType,
                     c=core.alt.Callback(kinematicSwitch.ikFkSwitch, obj, s,
                                         e))

        #-------
        # Spaces
        #-------
        if spaces:
            objsToSwitch = [obj]
            # Check if other selected objects have spaces to possibly swich to.
            sel = selected()
            if obj not in sel:
                sel.append(obj)

            if len(sel) > 1:
                allSpaces = []
                for o in sel:
                    tempSpaces = space.getNames(o)
                    if tempSpaces:
                        allSpaces.append(tempSpaces)

                if len(allSpaces) > 1:
                    objsToSwitch = sel
                    spaces = set(allSpaces[0]).intersection(allSpaces[1])

                    for t in allSpaces[2:]:
                        spaces.intersection_update(t)

            if spaces:
                menuItem(l='Switch space from %s to' %
                         obj.space.get(asString=True),
                         sm=True)
                for _space in sorted(spaces):
                    menuItem(l=_space,
                             c=Callback(switchSpaceGroup, objsToSwitch,
                                        _space))
                setParent('..', m=True)

        #-------
        # Main
        #-------
        """
        if lib.dagObj.simpleName(obj) == 'main':
            isMain = True
            if objExists(CONSTRAINT_SET_NAME):
                if PyNode(CONSTRAINT_SET_NAME).elements():
                    menuItem(l='Main Control Re-Lock', c=Callback(relockMain))
                else:
                    menuItem(l='Main Control Unlock', c=Callback(unlockMain))
            else:
                menuItem(l='Main Control Unlock', c=Callback(unlockMain))
                
            menuItem(l='Main Zero', sm=True)
            menuItem(l='All')
            for attr in [trans + axis for trans in 'tr' for axis in 'xyz']:
                skip = [trans + axis for trans in 'tr' for axis in 'xyz']
                skip.remove(attr)
                menuItem(l='Zero ' + attr, c=Callback(resetMain, skip))
            setParent('..', m=True)
                
        else:
            isMain = False
        
        # Divider, if needed
        if plug or len(spaces) > 1 or isMain:
            menuItem(d=True)
        """
    except Exception:
        print(traceback.format_exc())
Example #21
0
    def __init__(self):
    
        windowName = 'tpose_edit_adjustments'
        pdil.ui.deleteByName(windowName)
                

        self.settings = pdil.ui.Settings( 'Fossil Reposer GUI Settings',
            {
                'headers': [100, 40, 80],
                #geometry is added on close
            })
        
        objectName = 'Reposer'
        pdil.ui.deleteByName(objectName)
        
        super(GUI, self).__init__(pdil.ui.mayaMainWindow())
        
        self.setAttribute(Qt.QtCore.Qt.WA_DeleteOnClose) # Ensure it deletes instead of hides.
        
        self.setObjectName(windowName)
        scriptJob(p=windowName, e=('PostSceneRead', self.sceneChange))
        scriptJob(p=windowName, e=('NewSceneOpened', self.sceneChange))
        scriptJob(p=windowName, e=('SelectionChanged', self.selectionChanged))
        
        self.ui = ReposerGUI()
        self.ui.setupUi(self)
        
        self.ui.updateAll.clicked.connect(Callback(self.updateReposersWithProgress))
        self.ui.updateSelected.clicked.connect(Callback(self.runOnSelected, self.updateReposersWithProgress))
        
        self.ui.runAll.clicked.connect( Callback(self.runAdjustementsWithProgress) )
        self.ui.runSelected.clicked.connect( Callback(self.runOnSelected, self.runAdjustementsWithProgress) )
        
        self.setObjectName(objectName)
        self.setWindowTitle('Reposer')
        
        self.listAdjustments()
        
        self.entry = {0: {}, 1: {}, 2: {}}
        
        self.ui.cardChooser.currentTextChanged.connect(self.setOptions)
        self.ui.adjustmentChooser.addItems( [''] + [k for k in adjusters.adjustCommands.keys() if k[0] != '_']  )
        self.ui.adjustmentChooser.currentTextChanged.connect(self.setOptions)
        
        self.ui.addAdjustment.clicked.connect(self.addAdjustment)

        self.ui.removeAdjustment.clicked.connect(self.removeAdjustment)

        self.setOptions()
        
        # Load position settings
        header = self.ui.aligns.horizontalHeader()
        for col, width in enumerate(self.settings['headers']):
            header.resizeSection(col, width)
        
        self.show()
        
        if 'geometry' in self.settings:
            pdil.ui.setGeometry( self, self.settings['geometry'] )


        self.ui.aligns.cellChanged.connect(self.argUpdate)
Example #22
0
    def __init__(self, *args, **kwargs):
        
        self.settings = core.ui.Settings( 'Skeleton Tool Settings',
            {
                'spineCount': 5,
                'fingerCount': 4,
                'thumb': True,
                'spineOrient': 'Vertical',
                'legType': 'Human',
                'currentTabIndex': 1,  # 1-base AFAIK THE ONLY ONE ACTUALLY NEEDED
                'panels': [75, 75, 25, 100, 75, 25],
                'rebuildMode': 'Use Current Shapes',

                'closedControlFrame': False,
                'closeDebugFrame': True,
                
                # &&& This is really convoluted, storing the side map in two places.  Fix it on a rainy day.
                'joint_left': settings.JOINT_SIDE_CODE_MAP['left'],
                'joint_right': settings.JOINT_SIDE_CODE_MAP['right'],
                
                'control_left': settings.CONTROL_SIDE_CODE_MAP['left'],
                'control_right': settings.CONTROL_SIDE_CODE_MAP['right'],


                'showIndividualRestore': False,
                'showRigStateDebug': False,
            })
        
        objectName = 'Rig_Tool'
        # Remove any existing windows first
        core.ui.deleteByName(objectName)
        
        super(RigTool, self).__init__(core.ui.mayaMainWindow())
        
        # Not sure how else to get window's scale factor for high dpi displays
        self.scaleFactor = self.font().pixelSize() / 11.0

        self.ui = RigToolUI()
        self.ui.setupUi(self)

        self.setObjectName(objectName)
        self.setWindowTitle('Fossil')
        
        # Menu callbacks
        self.ui.actionReconnect_Real_Joints.triggered.connect( Callback(fossil_card.reconnectRealBones) )
        self.ui.actionMatch_Selected_Orients.triggered.connect( Callback(matchOrient) )
        
        self.ui.actionCard_Orients_2.triggered.connect( Callback(self.orientsToggle) )
        
        # &&& I think this isn't useful but I'm going to wait a while to be sure.
        #self.ui.actionConnectors.triggered.connect( Callback(self.connectorDisplayToggle) )
        self.ui.menuVisibility.removeAction(self.ui.actionConnectors)
        
        self.ui.actionHandles.triggered.connect( Callback(self.handleDisplayToggle) )
        
        self.ui.actionNaming_Rules.triggered.connect( Callback(self.nameRulesWindow) )
        
        self.ui.actionShow_Individual_Restores.setChecked( self.settings['showIndividualRestore'] )
        self.ui.actionShow_Card_Rig_State.setChecked( self.settings['showRigStateDebug'] )

        self.ui.actionShow_Individual_Restores.triggered.connect( Callback(self.restoreToggle) )
        self.ui.actionShow_Card_Rig_State.triggered.connect( Callback(self.rigStateToggle) )
                
        # Callback setup
        
        self.ui.makeCardBtn.clicked.connect(self.makeCard)
        self.ui.selectAllBtn.clicked.connect(self.selectAll)
        self.ui.buildBonesBtn.clicked.connect(self.buildBones)
        self.ui.deleteBonesBtn.clicked.connect( partial(util.runOnEach, operator.methodcaller('removeBones'), 'Bones deleted') )
        self.ui.buildRigBtn.clicked.connect( self.buildRig )
        self.ui.deleteRigBtn.clicked.connect( partial(util.runOnEach, operator.methodcaller('removeRig'), 'Rig deleted') )
        self.ui.saveModsBtn.clicked.connect( partial(util.runOnEach, operator.methodcaller('saveState'), 'State saved') )
        self.ui.restoreModsBtn.clicked.connect( partial(util.runOnEach, operator.methodcaller('restoreState'), 'State restored') )
        
        
        self.ui.duplicateCardBtn.clicked.connect(self.duplicateCard)
        self.ui.mergeCardBtn.clicked.connect(self.mergeCard)
        self.ui.splitCardBtn.clicked.connect(self.splitCard)

        self.ui.addCardIkButton.clicked.connect( self.addCardIk )
        self.ui.remCardIkButton.clicked.connect( self.removeCardIk )

        
        self.ui.insertJointBtn.clicked.connect(self.insertJoint)
        self.ui.addTipBtn.clicked.connect(partial(self.insertJoint, True))
        self.ui.deleteJointBtn.clicked.connect(self.deleteJoint)
        
        self.ui.rebuildProxyBtn.clicked.connect( proxy.rebuildConnectorProxy )
        
        self.ui.customUpBtn.clicked.connect(Callback(customUp))
        
        self.ui.updateRigState.clicked.connect(self.updateField)

        def restore(key, restoreFunc):
            print('Restoring', key)
            [ c._restoreData(restoreFunc, c.rigState[key]) for c in util.selectedCards() ]

        # Individual restore commands
        for niceName, harvestFunc, restoreFunc in nodeApi.Card.thingsToSave:
            button = getattr(self.ui, niceName + 'Restore')
            button.clicked.connect( partial(restore, niceName, restoreFunc))

        '''
        self.restoreShapes(objectSpace=shapesInObjectSpace)
        '''

        # Start Group Tab
        self.startTabLayout = Qt.QtWidgets.QVBoxLayout(self.ui.tab)
        self.startTabLayout.setObjectName( self.FOSSIL_START_TAB )
        setParent( self.FOSSIL_START_TAB )
        self.startTab = startingTab.StartLayout( self )
        
        
        # Vis Group Tab
        self.visGroupProxy = _visGroup.VisGroupLayout(self.ui)
        
        # Space Tab
        #self.spaceTabLayout = Qt.QtWidgets.QVBoxLayout(self.ui.space_tab)
        
        #self.spaceTabLayout.setObjectName( self.FOSSIL_SPACE_TAB )
        #setParent( self.FOSSIL_SPACE_TAB)
        #self.spaceTab = spacesTab.SpaceLayout()
        self.spaceTab = spacesTab.SpaceTab(self.ui)
        
        # Shelf tab
        
        
        self.artistShelfLayout = Qt.QtWidgets.QVBoxLayout(self.ui.artist_tools)
        self.artistShelfLayout.setObjectName( self.FOSSIL_ARTIST_TOOLS )
        setParent( self.FOSSIL_ARTIST_TOOLS )
        
        artistToolsTab.toolShelf()

        
        # Card Lister setup
        self.updateId = scriptJob( e=('SelectionChanged', core.alt.Callback(self.selectionChanged)) )
        self.ui.cardLister.setup(self.scaleFactor)
        
        self.ui.cardLister.itemSelectionChanged.connect(self.cardListerSelection)
        
        self.ui.cardLister.cardListerRefresh(force=True)
        self.ui.cardLister.updateHighlight()
        
        self.ui.jointLister.setup(self.scaleFactor)
        
        self.ui.cardLister.namesChanged.connect( self.ui.jointLister.jointListerRefresh )
        
        self.ui.restoreContainer.setVisible( self.settings['showIndividualRestore'] )
        self.ui.rigStateContainer.setVisible( self.settings['showRigStateDebug'] )

        # Controller Edit
        self.shapeEditor = controllerEdit.ShapeEditor(self)
        self.show()
        
        core.pubsub.subscribe(core.pubsub.Event.MAYA_DAG_OBJECT_CREATED, self.ui.cardLister.newObjMade)
    
        self.uiActive = True
        self._uiActiveStack = []
        
        self.ui.tabWidget.setCurrentIndex(self.settings['currentTabIndex'])
        
        if 'geometry' in self.settings:
            core.ui.setGeometry( self, self.settings['geometry'] )
Example #23
0
def reposeDeal():
    from pymel.core import window, rowColumnLayout, text, button, checkBox, showWindow, Callback, scrollLayout
    
    roots = getReposeRoots()

    allRepose = roots[:]
    for root in roots:
        allRepose += listRelatives(root, ad=True, type='transform')

    checks = {
        'origRot': [],
        'origTrans': [],
        'prevRot': [],
        'prevTrans': [],
        'prevRotWorld': [],
        'prevTransWorld': [],
    }

    attrs = {
        'origR': [ 'origRot', 'r' ],
        'origT': [ 'origTrans', 't' ],
        'prevR': [ 'prevRot', 'r' ],
        'prevT': [ 'prevTrans', 't' ],
        'prevRW': [ 'prevRotWorld', 'prevRW' ],
        'prevTW': [ 'prevTransWorld', 'prevTW' ],
    }

    def setValues(objs, checks, column):
        
        targets = [obj for obj, check in zip(objs, checks[column]) if check.getValue()]

        setValueHelper( column, targets )
        
        '''
        print(targets)
        for target in targets:
            print(target)
            if column == 'origR':
                target.r.set( target.origR.get() )
            elif column == 'origT':
                target.t.set( target.origTrans.get() )
                
            elif column == 'prevR':
                target.r.set( target.prevRot.get() )
            elif column == 'prevT':
                target.t.set( target.prevTrans.get() )
                
            else:
                raise Exception('IMPELEMNT WORLKD')
        '''

    window()
    with scrollLayout():
        with rowColumnLayout(nc=7):
            text(l='')

            button(l='origR', c=Callback( setValues, allRepose, checks, 'origRot') )
            button(l='origT', c=Callback( setValues, allRepose, checks, 'origTrans') )

            button(l='prevR', c=Callback( setValues, allRepose, checks, 'prevRot') )
            button(l='prevT', c=Callback( setValues, allRepose, checks, 'prevTrans') )

            button(l='prevRW', c=Callback( setValues, allRepose, checks, 'prevRW') )
            button(l='prevTW', c=Callback( setValues, allRepose, checks, 'prevTW') )
            
            for obj in allRepose:
                text(l=obj.name())
                checks['origRot'].append( checkBox(l='') )
                checks['origTrans'].append( checkBox(l='') )
                
                checks['prevRot'].append( checkBox(l='', v=not obj.origRot.get() == obj.prevRot.get() ) )
                checks['prevTrans'].append( checkBox(l='', v=not obj.origTrans.get() == obj.prevTrans.get() ) )

                checks['prevRotWorld'].append( checkBox(l='') )
                checks['prevTransWorld'].append( checkBox(l='') )

    showWindow()
Example #24
0
    def __init__(self):
        columnLayout()
        self.targets = textScrollList(nr=20, sc=Callback(self.targetSelected))

        rowColumnLayout(nc=2)
        button(l='   ^   ', c=Callback(self.moveUp))
        button(l='   v   ', c=Callback(self.moveDown))
        setParent("..")

        self.name = textFieldButtonGrp(l='Custom Name', bl='Update Existing')
        button(l="Add", c=Callback(self.addSpace, space.Mode.ROTATE_TRANSLATE))
        button(l="Add (Trans Only)",
               c=Callback(self.addSpace, space.Mode.TRANSLATE))
        button(l="Add ( No Rot )", c=Callback(self.addSpace, "#NOROT"))
        button(l="Add (No Trans)", c=Callback(self.addSpace, space.ROTATE))
        button(l="Split Targets (pos then rot)",
               c=Callback(self.addSpace, space.Mode.ALT_ROTATE))
        button(l="Multi/Vert targets", c=Callback(self.addMultiSpace))
        button(l="Multi Orient", c=Callback(self.addMultiOrientSpace))
        text(l='')
        button(l="Add Parent", c=Callback(self.addSpace, '#PARENT'))
        button(l="Add World", c=Callback(self.addSpace, '#WORLD'))
        button(l="Add True World", c=Callback(self.addSpace, '#TRUEWORLD'))
        button(l="Add External World (For attachments)",
               c=Callback(self.addSpace, '#EXTERNALWORLD'))
        button(l="Remove", c=Callback(self.remove))

        self.update()
        scriptJob(e=('SelectionChanged', Callback(self.update)), p=self.name)
Example #25
0
    def __init__(self):
        if window(self.name, ex=True):
            deleteUI(self.name)

        window(self.name)

        ass = formLayout()

        with tabLayout() as tab:
            tabLayout(tab,
                      e=True,
                      sc=lambda *args: setattr(self.settings, 'activeTab',
                                               tab.getSelectTabIndex()))
            with formLayout() as switcher:

                def setMode(modeName):
                    self.settings.mode = modeName

                self.rangeInput = radioButtonGrp(
                    nrb=4,
                    la4=[m.title() for m in self.MODES],
                    on1=Callback(setMode, self.MODES[0]),  # noqa e128
                    on2=Callback(setMode, self.MODES[1]),
                    on3=Callback(setMode, self.MODES[2]),
                    on4=Callback(setMode, self.MODES[3]),
                )

                self.rangeInput.setSelect(
                    self.MODES.index(self.settings.mode) + 1)

                with scrollLayout() as utilities:
                    with columnLayout(adj=True):

                        # Fk / Ik Switching
                        with frameLayout(l='Ik/Fk Switching',
                                         cll=True) as ikFkFrame:
                            self.settings.frameLayoutSetup(
                                ikFkFrame, 'ikfkCollapsed')
                            with rowColumnLayout(nc=3,
                                                 cw=[(1, 200), (2, 50),
                                                     (3, 50)]):
                                for card in core.findNode.allCards():
                                    for side in ['Center', 'Left', 'Right']:
                                        try:
                                            ik = card.getSide(side).ik
                                            fk = card.getSide(side).fk

                                            if ik and fk:
                                                text(l=ik.shortName())
                                                button(l='Ik',
                                                       c=Callback(
                                                           self.doIkFkSwitch,
                                                           fk, True))
                                                button(l='Fk',
                                                       c=Callback(
                                                           self.doIkFkSwitch,
                                                           ik, False))

                                        except Exception:
                                            print(traceback.format_exc())
                        """
                        # Space Switching
                        with frameLayout(l='Space Switching', cll=True) as spaceFrame:
                            self.settings.frameLayoutSetup(spaceFrame, 'spaceCollapsed')
                            with columnLayout() as self.main:
                                with rowColumnLayout( nc=2 ):
                                    
                                    button( l='Switch', c=Callback(self.switch) )
                                
                                text(l='Control')
                                self.targets = textScrollList(h=200)
                                scriptJob( e=('SelectionChanged', Callback(self.update)), p=self.main )
                                
                                text(l='')
                                
                                self.presetFileChooser = optionMenu(l='Presets', cc=Callback(self.loadSpace))
                                self.presetFiles = []
                                for folder in spacePresets.SpacePresets.folders:
                                    folder = os.path.expandvars(folder)
                                    
                                    if not os.path.exists(folder):
                                        continue
                                    
                                    for f in os.listdir(folder):
                                        if f.lower().endswith('.json'):
                                            cmds.menuItem(l=f[:-5])
                                            self.presetFiles.append( folder + '/' + f )
                                    
                                self.spacePresetList = textScrollList(h=100)
                                button(l='Apply', c=Callback(self.applySpacePreset))
                                
                                self.update()
                        """
                        """
                        # Main zeroing
                        with frameLayout(l='Zero Main Controller', cll=True) as zeroFrame:
                            self.settings.frameLayoutSetup(zeroFrame, 'zeroMainCollapsed')
                            with rowColumnLayout(nc=3):
                                with gridLayout(nrc=(2, 3)):
                                    toggles = []
                                    for attr in [t + a for t in 'tr' for a in 'xyz']:
                                        toggles.append( checkBox(l=attr) )
                                        self.settings.checkBoxSetup(toggles[-1], attr + '0')
                                    
                                    def setVal(val):
                                        for check in toggles:
                                            check.setValue(val)
                                        for attr in [t + a for t in 'tr' for a in 'xyz']:
                                            self.settings[attr + '0'] = val
                                        
                                with columnLayout(adj=True):
                                    button(l='All', c=Callback(setVal, True))
                                    button(l='Clear', c=Callback(setVal, False))

                                with columnLayout(adj=True):
                                    button(l='Apply', c=Callback(self.zeroMain))
                        """

                formLayout(
                    switcher,
                    e=True,
                    af=[  # noqa e128
                        (self.rangeInput, 'left', 0),
                        (self.rangeInput, 'top', 0),
                        (self.rangeInput, 'right', 0),
                        (utilities, 'left', 0),
                        (utilities, 'bottom', 0),
                        (utilities, 'right', 0),
                    ],
                    ac=(utilities, 'top', 0, self.rangeInput),
                )
            """
            with formLayout() as spaceTab:
                space = spacePresets.SpacePresets()
                
                formLayout(spaceTab, e=True,
                    af=[
                        (space.mainForm, 'top', 0),
                        (space.mainForm, 'bottom', 0),
                    ]
                )
                
                #button(save, e=True, c=Callback(space.save))
                #button(load, e=True, c=Callback(space.load))
            """

        #tabLayout(tab, e=True, tl=[(switcher, 'Switching'), (spaceTab, 'Spaces')] )
        tabLayout(tab, e=True, tl=[(switcher, 'Switching')])

        tabLayout(tab, e=True, sti=self.settings.activeTab)

        formLayout(
            ass,
            e=True,
            af=[  # noqa e128
                (tab, 'top', 0),
                (tab, 'left', 0),
                (tab, 'right', 0),
                (tab, 'bottom', 0),
            ])

        showWindow()
Example #26
0
    def __init__( self, ui ):
        self.ui = ui
        global gui
        gui = self

        buttonDirections = [
            ('Rename Space', (self.rename,), ''),
        
            '---',
        
            ('Add',                 [addSpace, space.Mode.ROTATE_TRANSLATE],
                    'Create a parent constraint'),
            ('Add (Trans Only)',    [addSpace, space.Mode.TRANSLATE],
                    'Create a translate contstraint'),
            ('Add ( No Rot )',      [addSpace, "#NOROT"],
                    'Follow the target as if it a parent constraint but do not inherit rotation'),
            ('Add (No Trans)',      [addSpace, space.Mode.ROTATE],
                    'Create an orient constraint'),
            ('Split Targets',       [addSpace, space.Mode.ALT_ROTATE],
                    'Follow the position of the first target, but the rotation of the second'),
            ('Multi/Vert targets',  (addMultiSpace,),
                    ''),
            ('Multi Orient',        (addMultiOrientSpace,),
                    ''),
            
            '---',
            
            ('Repeat',              (self.repeatSpace,), ''),
            
            '---',
            
            ('Add Parent',          [addSpace, '#PARENT'],
                    'Convenience to make a space following the actual hierarchical parent'),
            ('Add Main',            [addSpace, '#WORLD'],
                    'Convenience to follow the main controller'),
            ('Add World',           [addSpace, '#TRUEWORLD'],
                    'Convenience to stay in world space'),
            ('Add User Driven',     [addSpace, '#USER'],
                    'Generate a special node you can constrain and manipulate any way you want'),
            
            '---',
            
            ('Remove', (self.remove,), ''),
        ]
        
        self.buttonDirections = buttonDirections
        
        ROW_SPN = 1
        BTN_COL = 0
        BTN_SPN = 1
        
        USAGE_COL = 1
        USAGE_SPN = 3
        
        DIV_SPN = 4
        
        self.buttons = []

        for row, (label, funcArgs, usage) in enumerate(buttonDirections):
            if label == '-':
                divider = Qt.QtWidgets.QLabel(self.ui.space_tab)
                divider.setText('')
                self.ui.spaceQuickButtons.addWidget(divider, row, BTN_COL, ROW_SPN, DIV_SPN)
                continue
            
            button = Qt.QtWidgets.QPushButton(self.ui.space_tab)
            button.setText(label)
            if isinstance(funcArgs, list):
                funcArgs.append(row)
            button.clicked.connect( Callback(*funcArgs) )
            #button.setObjectName("addSpaceButton")
            self.ui.spaceQuickButtons.addWidget(button, row, BTN_COL, ROW_SPN, BTN_SPN)
            
            usageGuide = Qt.QtWidgets.QLabel(self.ui.space_tab)
            usageGuide.setText(usage)
            #usageGuide.setObjectName("addspaceLabel")
            self.ui.spaceQuickButtons.addWidget(usageGuide, row, USAGE_COL, ROW_SPN, USAGE_SPN)
            
            #button.setText(QtCompat.translate("MainWindow", "Add", None, -1))
            #usageGuide.setText(QtCompat.translate("MainWindow", "TextLabel", None, -1))

            self.buttons.append(button)
            
            if label == 'Repeat':
                self.repeatButton = button
            
        
        self.ui.spaceUp.clicked.connect( self.moveUp )
        self.ui.spaceDown.clicked.connect( self.moveDown )
        self.ui.spaceList.currentRowChanged.connect( self.targetSelected )
        
        self.update()
        
        self.jobId = scriptJob( e=('SelectionChanged', Callback(self.update)))
        
        self.updateRepeatSpace()
Example #27
0
    def __init__(self):
        self.main = columnLayout()  # Can't use `with since parent is QT`

        with rowColumnLayout(nc=2):
            self.targets = textScrollList(nr=20,
                                          sc=Callback(self.targetSelected))

            with frameLayout(l='Multi Weights') as self.multiUI:
                pass

        with rowColumnLayout(nc=2):
            button(l='   ^   ', c=Callback(self.moveUp))
            button(l='   v   ', c=Callback(self.moveDown))

        self.name = textFieldButtonGrp(l='Custom Name', bl='Update Existing')
        button(l='Add', c=Callback(self.addSpace, space.Mode.ROTATE_TRANSLATE))
        button(l='Add (Trans Only)',
               c=Callback(self.addSpace, space.Mode.TRANSLATE))
        button(l='Add ( No Rot )', c=Callback(self.addSpace, "#NOROT"))
        button(l='Add (No Trans)', c=Callback(self.addSpace, space.ROTATE))
        button(l='Split Targets (pos then rot)',
               c=Callback(self.addSpace, space.Mode.ALT_ROTATE))
        button(l='Multi/Vert targets', c=Callback(self.addMultiSpace))
        button(l='Multi Orient', c=Callback(self.addMultiOrientSpace))
        text(l='')
        button(l='Add Parent', c=Callback(self.addSpace, '#PARENT'))
        button(l='Add World', c=Callback(self.addSpace, '#WORLD'))
        button(l='Add True World', c=Callback(self.addSpace, '#TRUEWORLD'))
        #button( l='Add External World (For attachments)', c=Callback(self.addSpace, '#EXTERNALWORLD') )
        button(l='Add User Driven', c=Callback(self.addSpace, '#USER'))
        button(l='Remove', c=Callback(self.remove))

        self.update()
        scriptJob(e=('SelectionChanged', Callback(self.update)), p=self.main)
Example #28
0
    def __init__(self, *args, **kwargs):
        global settings

        objectName = 'Rig_Tool'
        # Remove any existing windows first
        core.ui.deleteByName(objectName)

        super(RigTool, self).__init__(core.ui.mayaMainWindow())

        self.ui = RigToolUI()
        self.ui.setupUi(self)

        self.setObjectName(objectName)
        self.setWindowTitle('Fossil')

        # Menu callbacks
        self.ui.actionReconnect_Real_Joints.triggered.connect(
            Callback(fossil_card.reconnectRealBones))
        self.ui.actionMatch_Selected_Orients.triggered.connect(
            Callback(matchOrient))

        self.ui.actionCard_Orients_2.triggered.connect(
            Callback(self.orientsToggle))

        # &&& I think this isn't useful but I'm going to wait a while to be sure.
        #self.ui.actionConnectors.triggered.connect( Callback(self.connectorDisplayToggle) )
        self.ui.menuVisibility.removeAction(self.ui.actionConnectors)

        self.ui.actionHandles.triggered.connect(
            Callback(self.handleDisplayToggle))
        '''
        button(l="Custom Up", c=Callback(customUp), w=200)
    
        '''

        # Callback setup

        self.ui.makeCardBtn.clicked.connect(self.makeCard)
        self.ui.selectAllBtn.clicked.connect(self.selectAll)
        self.ui.buildBonesBtn.clicked.connect(self.buildBones)
        self.ui.deleteBonesBtn.clicked.connect(
            partial(util.runOnEach, operator.methodcaller('removeBones'),
                    'Bones deleted'))
        self.ui.buildRigBtn.clicked.connect(self.buildRig)
        self.ui.deleteRigBtn.clicked.connect(
            partial(util.runOnEach, operator.methodcaller('removeRig'),
                    'Rig deleted'))
        self.ui.saveModsBtn.clicked.connect(
            partial(util.runOnEach, operator.methodcaller('saveState'),
                    'State saved'))
        self.ui.restoreModsBtn.clicked.connect(
            partial(util.runOnEach, operator.methodcaller('restoreState'),
                    'State restored'))

        self.ui.duplicateCardBtn.clicked.connect(self.duplicateCard)
        self.ui.mergeCardBtn.clicked.connect(self.mergeCard)
        self.ui.splitCardBtn.clicked.connect(self.splitCard)

        self.ui.insertJointBtn.clicked.connect(self.insertJoint)
        self.ui.addTipBtn.clicked.connect(partial(self.insertJoint, True))
        self.ui.deleteJointBtn.clicked.connect(self.deleteJoint)

        self.ui.rebuildProxyBtn.clicked.connect(proxy.rebuildConnectorProxy)

        self.ui.customUpBtn.clicked.connect(Callback(customUp))

        # Start Group Tab
        self.startTabLayout = Qt.QtWidgets.QVBoxLayout(self.ui.tab)
        self.startTabLayout.setObjectName(self.FOSSIL_START_TAB)
        setParent(self.FOSSIL_START_TAB)
        self.startTab = startingTab.StartLayout(self)

        # Vis Group Tab
        self.visGroupProxy = _visGroup.VisGroupLayout(self.ui)

        # Space Tab
        self.spaceTabLayout = Qt.QtWidgets.QVBoxLayout(self.ui.space_tab)

        self.spaceTabLayout.setObjectName(self.FOSSIL_SPACE_TAB)
        setParent(self.FOSSIL_SPACE_TAB)
        self.spaceTab = spacesTab.SpaceLayout()

        # Shelf tab

        self.artistShelfLayout = Qt.QtWidgets.QVBoxLayout(self.ui.artist_tools)
        self.artistShelfLayout.setObjectName(self.FOSSIL_ARTIST_TOOLS)
        setParent(self.FOSSIL_ARTIST_TOOLS)

        artistToolsTab.toolShelf()

        # Card Lister setup
        self.updateId = scriptJob(e=('SelectionChanged',
                                     core.alt.Callback(self.selectionChanged)))
        self.ui.cardLister.setup()

        self.ui.cardLister.itemSelectionChanged.connect(
            self.cardListerSelection)

        self.ui.cardLister.cardListerRefresh(force=True)
        self.ui.cardLister.updateHighlight()

        self.ui.jointLister.setup()

        self.ui.cardLister.namesChanged.connect(
            self.ui.jointLister.jointListerRefresh)

        # Controller Edit
        self.shapeEditor = controllerEdit.ShapeEditor(self)
        self.show()

        core.pubsub.subscribe(core.pubsub.Event.MAYA_DAG_OBJECT_CREATED,
                              self.ui.cardLister.newObjMade)

        self.uiActive = True
        self._uiActiveStack = []
Example #29
0
    def hookupSignals(self):
        # Scaling
        self.minus_one.clicked.connect(Callback(self.scaleCvs, 0.99))
        self.minus_ten.clicked.connect(Callback(self.scaleCvs, 0.90))
        self.plus_ten.clicked.connect(Callback(self.scaleCvs, 1.10))
        self.plus_one.clicked.connect(Callback(self.scaleCvs, 1.01))

        # Rotating
        self.rot_local_x.clicked.connect(
            Callback(self.rotate, 'x', 45, 'local'))
        self.rot_local_y.clicked.connect(
            Callback(self.rotate, 'y', 45, 'local'))
        self.rot_local_z.clicked.connect(
            Callback(self.rotate, 'z', 45, 'local'))
        self.rot_world_x.clicked.connect(
            Callback(self.rotate, 'x', 45, 'world'))
        self.rot_world_y.clicked.connect(
            Callback(self.rotate, 'y', 45, 'world'))
        self.rot_world_z.clicked.connect(
            Callback(self.rotate, 'z', 45, 'world'))

        # Selecting
        self.select_cvs.clicked.connect(Callback(self.selectCVs))
        self.select_pin_head.clicked.connect(Callback(self.selectPinHead))
        self.select_band_edge_1.clicked.connect(Callback(self.bandEdge, 1))
        self.select_band_edge_2.clicked.connect(Callback(self.bandEdge, 2))

        # Shapes
        self.copyShapes.clicked.connect(Callback(self.transferShape))
        self.mirrorShapes.clicked.connect(
            Callback(self.transferShape, mirror=True))
        self.mirrorSide.clicked.connect(
            Callback(lambda: mirrorAllKinematicShapes(selected()[0])))

        #self.mirrorSide.setContextMenuPolicy(Qt.QtCore.Qt.CustomContextMenu)
        #self.mirrorSide.customContextMenuRequested.connect(self.XXXcontextMenuEvent)

        self.copyToCBBtn.clicked.connect(Callback(self.copyToClipboad))
        self.pasteLocalBtn.clicked.connect(
            Callback(self.pasteFromCliboard, 'os'))
        self.pasteWorldBtn.clicked.connect(
            Callback(self.pasteFromCliboard, 'ws'))