예제 #1
0
	def S(self):
		if cmds.currentCtx() == 'polySlideEdgeContext':
			cmds.setToolTo ('polySelectEditContext')
		elif cmds.currentCtx() == 'polySelectEditContext':
			cmds.setToolTo ('polySlideEdgeContext')
		else:
			if self.getType(0) == 'edge':
				try:
					self.bridgeTool()
				except RuntimeError:
					cmds.setToolTo('polySlideEdgeContext')
			elif cmds.selectType(q=1, polymeshVertex = True) == True: #check to see if mask type is vertex
				self.vertexMergeTool()
			elif self.getType(0) == 'face':
				self.chipFacesTool()
			elif self.getType(0) == 'mesh':
				if len(self.getSelection()) == 1:
					self.polySeperateTool() # seperate because there's only one poly selected
				else:
					self.polyMergeTool() # merge because there's more than one poly selected
			elif self.getType(0)[0] == 'camera':
				print 'yes it is'
				self.cameraShakeTool()
			else:
				cmds.setToolTo ('polySelectEditContext')
예제 #2
0
 def clear(self, *args):
     
     
     if cmds.iconTextButton("TempCustomPivotBtn", query=True, exists=True):
         cmds.iconTextButton("TempCustomPivotBtn", edit=True, image= uiMod.getImagePath("specialTools_create_temp_custom_pivot"),         highlightImage= uiMod.getImagePath("specialTools_create_temp_custom_pivot copy"))
            
     cmds.refresh(suspend=True)
     
     currFrame = cmds.currentTime(query=True) 
     
     loadConstraints = aToolsMod.loadInfoWithScene(self.STORE_NODE, self.CONSTRAINTS)
     loadLocators    = aToolsMod.loadInfoWithScene(self.STORE_NODE, self.LOCATORS)
     loadCtrls       = aToolsMod.loadInfoWithScene(self.STORE_NODE, self.CTRLS)
     currentFrame    = aToolsMod.loadInfoWithScene(self.STORE_NODE, self.CURRENTFRAME)
     
     #exit edit mode
     
     if cmds.currentCtx() not in self.deniedCtx: cmds.setToolTo(cmds.currentCtx())
     
     
     if currentFrame:
         cmds.currentTime(eval(currentFrame))
     
     #get values
     """
     translation = []
     rotation    = []
     if loadCtrls: 
         ctrlObjs    = eval(loadCtrls)
         for loopCtrl in ctrlObjs:
             translation.append(cmds.xform(loopCtrl, query=True, ws=True, rotatePivot=True))
             rotation.append(cmds.xform(loopCtrl, query=True, ws=True, rotation=True))
     """        
     
     
     if loadConstraints: 
         constraintObjs = eval(loadConstraints)
         for loopConstraint in constraintObjs:
             if cmds.objExists(loopConstraint): cmds.delete(loopConstraint)
             
     if loadCtrls and loadLocators: 
         locatorObjs = eval(loadLocators)
         ctrlObjs    = eval(loadCtrls)
         for n, loopCtrl in enumerate(ctrlObjs):
             if cmds.objExists(loopCtrl) and cmds.objExists(locatorObjs[n]):
                 G.aToolsBar.align.align([loopCtrl], locatorObjs[n]) 
     
         for loopLocator in locatorObjs:
             if cmds.objExists(loopLocator): cmds.delete(loopLocator)
     
     cmds.currentTime(currFrame)    
     cmds.refresh(suspend=False)
예제 #3
0
	def smoothBetweenSelectedJoints( self ):
		'''
		performs a flood smooth between the selected joints
		'''

		#grab initial state
		initialLockState = [ cmd.getAttr( '%s.liw' % j ) for j in self.UI_tsl ]
		initMode = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, sao=True )
		initOpacity = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, opacity=True )
		initValue = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, value=True )

		self.setLockStateForAll( True, False )
		self.setLockStateForSelected( False, False )


		#perform the smooth
		cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, sao='smooth' )
		j = self.iterSelected().next()
		if j is not None:
			cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, value=1, opacity=1, clear=True )


		#restore state
		cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, sao=initMode )
		cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, opacity=initOpacity )
		cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, value=initValue )
		for j, state in zip( self.UI_tsl, initialLockState ):
			cmd.setAttr( '%s.liw' % j, state )
def bevel():
    """
    Bevel is a collection of functions usually performed when certain states
    are fulfilled, such as: selection, border edge etc.
    """
    selected = mampy.complist()
    if not selected:
        raise NothingSelected()

    component = selected[0]
    # Eearly return in case of map components
    if component.type == MFn.kMeshMapComponent:
        raise InvalidComponentSelection()

    if component.type == api.MFn.kMeshEdgeComponent:
        # Check if we can extrude edge borders or bevel internal edges.
        if all(component.is_border(i) for i in component.indices):
            # When extruding border edges we don't want the context tool to handle
            # the manipulation. Just restore old tool right away.
            with restore_context():
                dragger_contexts.Extrude().execute()
        elif not any(component.is_border(i) for i in component.indices):
            dragger_contexts.Bevel().set_context()
        else:
            raise InvalidSelection('Mixed selections, cant mix edge borders with '
                                   'non borders when beveling.')
    else:
        # Else perform an extrude on polygon or vertex.
        if cmds.currentCtx() == dragger_contexts.Extrude.NAME:
            dragger_contexts.Extrude().execute()
        else:
            dragger_contexts.Extrude().set_context()
예제 #5
0
def exit_tool_and_mask():
    """Exit current tool or toggle selection mode.

    When working with other contexts in maya use this function to exit the current
    context and return to selection context; if you are using base tools ('select',
    move, rotate, scale) toggle selection mode instead.

    Usage:

        tool_select()

    """
    # base_tools = ['{}SuperContext'.format(i) for i in ('select', 'move', 'rotate', 'scale')]
    if not cmds.currentCtx() == 'selectSuperContext':
        cmds.setToolTo('selectSuperContext')
    else:
        if cmds.selectMode(q=True, object=True):
            hilited = mampy.daglist(hl=True)
            if hilited:
                cmds.hilite(hilited.cmdslist(), toggle=True)
                cmds.select(hilited.cmdslist())
            else:
                cmds.selectMode(component=True)
        else:
            cmds.selectMode(object=True)
예제 #6
0
	def newItemJob(self):
		# Reset the object creation handling job 
		if(cmds.scriptJob(exists=self.newObjectJob)):
			cmds.scriptJob(kill=self.newObjectJob)
		self.newObjectJob = cmds.scriptJob(event=('DagObjectCreated', self.onNewObject))
		# Store the current tool so we can change back to it when the user has finished painting
		self.currentContext = cmds.currentCtx()
예제 #7
0
	def on_selectJoint( self, *a ):
		if cmd.currentCtx() == 'artAttrSkinContext':
			selJ = self.iterSelected().next()
			if selJ is None:
				return

			mel.artSkinSelectInfluence( 'artAttrSkinPaintCtx', selJ, selJ )
예제 #8
0
 def _addKey(self, value=None):
     """trigger for adding new key into cluster"""
     if self._key == "panel":
         if value == "enter manually...":
             key = raw_input().replace(" ", "")
         else:
             key = value
     elif self._key == "name":
         key = raw_input().replace(" ", "")
     elif self._key == "preset":
         key = raw_input()
     elif self._key == "dag":
         key = " ".join(self._engine.findDagKey())
         if not self._line_prefix.text() or not key:
             return
         key = "%s %s" % (self._line_prefix.text(), key)
     elif self._key == "non dag":
         key = " ".join(self._engine.findNonDagKey())
         if not self._line_prefix.text() or not key:
             return
         key = "%s %s" % (self._line_prefix.text(), key)
     elif self._key == "tool":
         if not self._line_prefix.text():
             return
         key = "%s %s" % (self._line_prefix.text(), cmds.currentCtx())
     else:
         return
     if key and key not in self._nodes:
         self._nodes[key] = Engine.DefaultData.node()
         self._list_keys.addItem(key)
예제 #9
0
	def __init__( self ):
		self.ButtonIsStart 				= False
		self.ObjectPicked				= None
		self.RotatePosition		    	= MTVector( 0.0, 0.0, 0.0 ) 
		self.RotateAroundSelected 		= -1
		self.SelectedObjects        	= None
		self.ObjectsToRotate        	= None
		self.IgnoreSelectionChangeEvent	= False
		self.CloseButtonPressed 		= False	
		self.DummyNode					= None
		self.CurrentContext				= None
		
		self.BuildUI()
		self.OnRotateAroundCenterBBoxSelected( None )
		self.OnSelectionChange()
		
		self.SelectionJob = cmds.scriptJob( event = ( "SelectionChanged", self.OnSelectionChange ), parent = self.Window )
		self.DeleteJob    = cmds.scriptJob( uiDeleted = ( self.Window, self.OnWindowClosed ) )
		
		# se crea un nodo invisible que servira para obtener las rotaciones de mundo
		self.DummyNode = cmds.createNode( "transform", skipSelect = True )		
		
		# nuevo rotator para saber cuando se termina de girar
		self.CurrentContext = cmds.currentCtx()
		self.ManipRotate = cmds.manipRotateContext( mode = 1, postDragCommand = ( self.OnObjectRotated, "transform" ) )	
예제 #10
0
 def _findToolNode(self):
     """find current tool node"""
     context = cmds.currentCtx()  # context marking menu
     panel = cmds.getPanel(underPointer=True)
     for panel in panel, panel.rstrip(string.digits), "any":
         if "%s %s" % (panel, context) in self.cluster["tool"]:
             return self.cluster["tool"]["%s %s" % (panel, context)]
     return self.EMPTY_NODE
예제 #11
0
 def makeLocOnSel(self):
     tool = cmds.currentCtx()
     cmds.setToolTo( 'moveSuperContext' )
     pos = cmds.manipMoveContext( 'Move', q=True, p=True )
     startLoc = cmds.spaceLocator (n = ('skinWrangler_jointBboxLocator'))[0]
     cmds.move(pos[0] ,pos[1] ,pos[2] ,startLoc, ws = 1 , a =1)
     cmds.setToolTo(tool)
     return startLoc
예제 #12
0
def tool():
    """trigger for changed tool"""
    current_tool = cmds.currentCtx()
    if current_tool not in last_tools_set:
        last_tools_set.add(current_tool)
        last_tools_list.append(current_tool)
    while len(last_tools_list) > 8:
        last_tools_set.discard(last_tools_list.pop(0))
예제 #13
0
 def closeTool(s, sel):
     """
     Remove mesh highlighting etc when tool officially stops.
     """
     if cmds.currentCtx() != s.tool and s.active:
         s.active = False
         s.setColour()
         if s.lastControl:
             cmds.setAttr(s.lastControl, 0)
예제 #14
0
    def joint_tool_context(self):
        if cmds.currentCtx() == self.current_tool_context:
            return

        context_string = self.set_context_index('jointContext')

        cmds.jointCtx(context_string)
        cmds.setToolTo(context_string)
        self.current_tool_context = context_string
        print 'Context set to %s' % context_string
예제 #15
0
def _disable():
    _delete_script_jobs()

    for t in TOOLS.all():
        if cmds.currentCtx() == t:
            cmds.setToolTo('selectSuperContext')
        if cmds.contextInfo(t, exists=True):
            cmds.deleteUI(t)

    tc_motion_path_widget.set_active_tool('selectSuperContext')
예제 #16
0
	def syncSelection( self ):
		'''
		syncs the list selection with the existing paint skin weights UI
		'''
		cur = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, inf=True )
		if cur is None:
			return

		self.UI_tsl.clearSelection()
		self.UI_tsl.selectByValue( cur )
    def __init__(self, icon_path, maya_tool_name, parent=None):
        super(EditButton, self).__init__(parent=parent)
        self.setFixedSize(40, 40)
        self.setCheckable(True)
        self.setToolTip(TOOLS.tooltip(maya_tool_name))

        self.setIcon(QtGui.QIcon(icon_path))
        self.setIconSize(QtCore.QSize(38, 38))
        self._maya_tool_name = maya_tool_name
        self._previous_context = cmds.currentCtx()

        self.clicked.connect(self._clicked)
예제 #18
0
 def load(s):
     sel = cmds.ls(sl=True)
     if sel and sel[0] in s.valid:
         s.sel = sel[0]
         s.tool = cmds.currentCtx()
         s.myTool = "TempTool"
         if cmds.draggerContext(s.myTool, exists=True):
             cmds.deleteUI(s.myTool)
         cmds.draggerContext(s.myTool, name=s.myTool, pressCommand=s.click, cursor='hand')
         cmds.setToolTo(s.myTool)
         print "Make a selection"
     else:
         print "Nothing selected"
예제 #19
0
 def selectUpdate(s, sel):
     if s.selection:
         if cmds.currentCtx() != s.picker.tool:
             if sel and len(sel) == 1:
                 if sel[0] in s.selection:
                     # Turn on our picker!!
                     print "Turning on Picker"
                     s.select.ignore = True
                     # Make the mesh look different to make it obvious
                     # That we're doing something with it.
                     s.picker.switchTool(sel[0])
                     cmds.select(clear=True)
                     cmds.refresh()
예제 #20
0
def setupMannequinUI():
    """Sets up the side panel UI for the Mannequin plugin."""

    currentContext = cmds.currentCtx()
    influenceObjectsStr = cmds.mannequinContext(currentContext,
                                                q=True,
                                                io=True)
    ioTokens = influenceObjectsStr.split(" ")
    ioDagPaths = ioTokens[::2]
    ioAvailableStyles = ioTokens[1::2]

    mannequinDockPtr = MQtUtil.findLayout("mannequinPaletteDock")
    mannequinDock = wrapInstance(long(mannequinDockPtr), QWidget)
    mannequinDock.setMinimumWidth(300)

    mannequinLayoutPtr = MQtUtil.findLayout("mannequinPaletteLayout")
    mannequinLayout = wrapInstance(long(mannequinLayoutPtr), QWidget)

    mannequinSearchPtr = MQtUtil.findControl("mannequinSearchField")
    mannequinSearch = wrapInstance(long(mannequinSearchPtr), QLineEdit)

    uiFile = QFile(os.path.join(os.path.dirname(__file__), "mannequin.ui"))
    uiFile.open(QFile.ReadOnly)
    gui = mannequinToolPanel.loader.load(uiFile, parentWidget=mannequinLayout)
    uiFile.close()

    selList = om.MSelectionList()
    for obj in ioDagPaths:
        selList.add(obj)

    joints = []
    for i in range(selList.length()):
        dagPath = selList.getDagPath(i)
        dependNode = selList.getDependNode(i)
        styles = ioAvailableStyles[i]

        joints.append(JointInfo(dagPath, dependNode, styles))

    # Alphabetize joints by full DAG path; should sort slightly better.
    joints = sorted(joints, key=lambda j: j.dagPath.fullPathName())

    prefixTrim = commonPrefix(joints)
    mannequinToolPanel.reset(mannequinLayout,
                             gui,
                             mannequinSearch,
                             prefixTrim)

    jointDisplays = organizeJoints(joints)
    for jointDisplay in jointDisplays:
        mannequinToolPanel.layoutJointGroup(jointDisplay)
    mannequinToolPanel.finishLayout()
예제 #21
0
    def tool_changed(self, *args):

        current_tool = cmds.currentCtx()
        if not current_tool.startswith('spore'):
            try:
                cmds.button('placeBtn', e=True, bgc=(0.366, 0.366, 0.366))
                cmds.button('sprayBtn', e=True, bgc=(0.366, 0.366, 0.366))
                cmds.button('scaleBtn', e=True, bgc=(0.366, 0.366, 0.366))
                cmds.button('alignBtn', e=True, bgc=(0.366, 0.366, 0.366))
                #  cmds.button('moveBtn', e=True, bgc=(0.366, 0.366, 0.366))
                cmds.button('idBtn', e=True, bgc=(0.366, 0.366, 0.366))
                cmds.button('removeBtn', e=True, bgc=(0.366, 0.366, 0.366))
            except RuntimeError:
                pass
예제 #22
0
def run(parent):
    try:
        context = cmds.currentCtx()
        mode = getMode(context)
        cmds.setParent(parent, menu=True)
        cmds.radioMenuItemCollection()
        cmds.menuItem(label="snap off", rb=mode == 0, rp="NW", c=wrapper(context, 0))
        cmds.menuItem(label="snap relative", rb=mode == 1, rp="N", c=wrapper(context, 1))
        cmds.menuItem(label="snap absolute", rb=mode == 2, rp="NE", c=wrapper(context, 2))
        new_mode = 1 if mode == 0 else mode
        for value, pos in zip(values[context], positions):
            cmds.menuItem(label=str(value), rp=pos, c=wrapper(context, new_mode, value))
    except KeyError:
        pass
예제 #23
0
def smoothFlood(skinCluster, iterations=1):
    '''
	Smooth flood all influences
	@param geometry: The geometry connected to the skinCluster to smooth
	@type geometry: str
	@param iterations: Number of smooth iterations
	@type iterations: int
	'''
    # Check zero iterations
    if not iterations: return

    # Get current tool
    currentTool = mc.currentCtx()

    # Select geometry
    geometry = glTools.utils.deformer.getAffectedGeometry(skinCluster).keys()
    mc.select(geometry)

    # Get skinCluster influence list
    influenceList = mc.skinCluster(skinCluster, q=True, inf=True)

    # Unlock influence weights
    for influence in influenceList:
        mc.setAttr(influence + '.lockInfluenceWeights', 0)

    # Initialize paint context
    skinPaintTool = 'artAttrSkinContext'
    if not mc.artAttrSkinPaintCtx(skinPaintTool, ex=True):
        mc.artAttrSkinPaintCtx(skinPaintTool,
                               i1='paintSkinWeights.xpm',
                               whichTool='skinWeights')
    mc.setToolTo(skinPaintTool)
    mc.artAttrSkinPaintCtx(skinPaintTool, edit=True, sao='smooth')

    # Smooth Weights
    for i in range(iterations):
        print(skinCluster + ': Smooth Iteration - ' + str(i + 1))
        for influence in influenceList:
            # Lock current influence weights
            mc.setAttr(influence + '.lockInfluenceWeights', 1)
            # Smooth Flood
            mm.eval('artSkinSelectInfluence artAttrSkinPaintCtx "' +
                    influence + '" "' + influence + '"')
            mc.artAttrSkinPaintCtx(skinPaintTool, e=True, clear=True)
            # Unlock current influence weights
            mc.setAttr(influence + '.lockInfluenceWeights', 0)

    # Reset current tool
    mc.setToolTo(currentTool)
예제 #24
0
def set_commands(node_type='transform', pre_func=str, post_func=str):
    mc.manipMoveContext('Move', e=True, preDragCommand=[pre_func, node_type])
    mc.manipMoveContext('Move', e=True, postDragCommand=[post_func, node_type])
    mc.manipRotateContext('Rotate',
                          e=True,
                          preDragCommand=[pre_func, node_type])
    mc.manipRotateContext('Rotate',
                          e=True,
                          postDragCommand=[post_func, node_type])
    mc.manipScaleContext('Scale', e=True, preDragCommand=[pre_func, node_type])
    mc.manipScaleContext('Scale',
                         e=True,
                         postDragCommand=[post_func, node_type])
    # the drag commands are only active on reentering the context
    mc.setToolTo(mc.currentCtx())
예제 #25
0
def autoPivot():
    #Query what tool the user has selected
    tool = Maya.currentCtx(q=True)
    #Maya.setToolTo(tool)

    #Current tool is rotate tool
    if tool == 'RotateSuperContext':
        animPivot()

    #Current tool is move tool
    elif tool == 'moveSuperContext':
        matchScript()

    #Call our snapCommand() script
    snapCommand()
예제 #26
0
def setupMannequinUI():
    """Sets up the side panel UI for the Mannequin plugin."""

    currentContext = cmds.currentCtx()
    influenceObjectsStr = cmds.mannequinContext(currentContext,
                                                q=True,
                                                io=True)
    ioTokens = influenceObjectsStr.split(" ")
    ioDagPaths = ioTokens[::2]
    ioAvailableStyles = ioTokens[1::2]

    mannequinDockPtr = MQtUtil.findLayout("mannequinPaletteDock")
    mannequinDock = wrapInstance(long(mannequinDockPtr), QWidget)
    mannequinDock.setMinimumWidth(300)

    mannequinLayoutPtr = MQtUtil.findLayout("mannequinPaletteLayout")
    mannequinLayout = wrapInstance(long(mannequinLayoutPtr), QWidget)

    mannequinSearchPtr = MQtUtil.findControl("mannequinSearchField")
    mannequinSearch = wrapInstance(long(mannequinSearchPtr), QLineEdit)

    uiFile = QFile(os.path.join(os.path.dirname(__file__), "mannequin.ui"))
    uiFile.open(QFile.ReadOnly)
    gui = mannequinToolPanel.loader.load(uiFile, parentWidget=mannequinLayout)
    uiFile.close()

    selList = om.MSelectionList()
    for obj in ioDagPaths:
        selList.add(obj)

    joints = []
    for i in range(selList.length()):
        dagPath = selList.getDagPath(i)
        dependNode = selList.getDependNode(i)
        styles = ioAvailableStyles[i]

        joints.append(JointInfo(dagPath, dependNode, styles))

    # Alphabetize joints by full DAG path; should sort slightly better.
    joints = sorted(joints, key=lambda j: j.dagPath.fullPathName())

    prefixTrim = commonPrefix(joints)
    mannequinToolPanel.reset(mannequinLayout, gui, mannequinSearch, prefixTrim)

    jointDisplays = organizeJoints(joints)
    for jointDisplay in jointDisplays:
        mannequinToolPanel.layoutJointGroup(jointDisplay)
    mannequinToolPanel.finishLayout()
예제 #27
0
    def update_brush_btn(self, attr):

        cmds.button('placeBtn',
                    e=True,
                    bgc=(0.366, 0.366, 0.366),
                    c=pm.Callback(self.activateContext, 'place', attr, 0))
        cmds.button('sprayBtn',
                    e=True,
                    bgc=(0.366, 0.366, 0.366),
                    c=pm.Callback(self.activateContext, 'spray', attr, 1))
        cmds.button('scaleBtn',
                    e=True,
                    bgc=(0.366, 0.366, 0.366),
                    c=pm.Callback(self.activateContext, 'scale', attr, 2))
        cmds.button('alignBtn',
                    e=True,
                    bgc=(0.366, 0.366, 0.366),
                    c=pm.Callback(self.activateContext, 'align', attr, 3))
        cmds.button('moveBtn',
                    e=True,
                    bgc=(0.366, 0.366, 0.366),
                    c=pm.Callback(self.activateContext, 'move', attr, 4))
        cmds.button('idBtn',
                    e=True,
                    bgc=(0.366, 0.366, 0.366),
                    c=pm.Callback(self.activateContext, 'id', attr, 5))
        cmds.button('removeBtn',
                    e=True,
                    bgc=(0.366, 0.366, 0.366),
                    c=pm.Callback(self.activateContext, 'remove', attr, 6))

        self._node = attr.split('.')[0]
        if cmds.currentCtx().startswith('spore'):
            ctx_mode = cmds.getAttr(attr)
            if ctx_mode == 0:
                cmds.button('placeBtn', e=True, bgc=(0.148, 0.148, 0.148))
            elif ctx_mode == 1:
                cmds.button('sprayBtn', e=True, bgc=(0.148, 0.148, 0.148))
            elif ctx_mode == 2:
                cmds.button('scaleBtn', e=True, bgc=(0.148, 0.148, 0.148))
            elif ctx_mode == 3:
                cmds.button('alignBtn', e=True, bgc=(0.148, 0.148, 0.148))
            elif ctx_mode == 4:
                cmds.button('moveBtn', e=True, bgc=(0.148, 0.148, 0.148))
            elif ctx_mode == 5:
                cmds.button('idBtn', e=True, bgc=(0.148, 0.148, 0.148))
            elif ctx_mode == 6:
                cmds.button('removeBtn', e=True, bgc=(0.148, 0.148, 0.148))
	def disable(self):
		
		# Set default context
		if mc.currentCtx() == self.context:
			mc.setToolTo('moveSuperContext')
		
			# Restore user selection
			if len(self.userSelection):
				mc.select(self.userSelection)
			else:
				mc.select(cl=1)
			
			# Clear user selection
			self.userSelection = []
			
			print('Edit Membership context disabled!')
예제 #29
0
def setManipCommands(nodeType='transform', preFunc=str, postFunc=str):
    mc.manipMoveContext('Move', e=True, preDragCommand=[preFunc, nodeType])
    mc.manipMoveContext('Move', e=True, postDragCommand=[postFunc, nodeType])
    mc.manipRotateContext('Rotate', e=True, preDragCommand=[preFunc, nodeType])
    mc.manipRotateContext('Rotate',
                          e=True,
                          postDragCommand=[postFunc, nodeType])
    mc.manipScaleContext('Scale', e=True, preDragCommand=[preFunc, nodeType])
    mc.manipScaleContext('Scale', e=True, postDragCommand=[postFunc, nodeType])
    # the drag commands are only active on reentering the context
    currentCtx = mc.currentCtx()
    if currentCtx in [
            'moveSuperContext', 'RotateSuperContext', 'scaleSuperContext'
    ]:
        # only set context if needed
        mc.setToolTo(currentCtx)
예제 #30
0
 def load(s):
     sel = cmds.ls(sl=True)
     if sel and sel[0] in s.valid:
         s.sel = sel[0]
         s.tool = cmds.currentCtx()
         s.myTool = "TempTool"
         if cmds.draggerContext(s.myTool, exists=True):
             cmds.deleteUI(s.myTool)
         cmds.draggerContext(s.myTool,
                             name=s.myTool,
                             pressCommand=s.click,
                             cursor='hand')
         cmds.setToolTo(s.myTool)
         print "Make a selection"
     else:
         print "Nothing selected"
예제 #31
0
def set_active_axes(axis='center'):
    try:
        ctx = cmds.currentCtx()
        manip = {cls.type_: cls for cls in BaseManip.__subclasses__()}[ctx]()
    except KeyError:
        return logger.warn('Supports move, scale and rotate super context')
    dispatch = {
        'x': 0,
        'y': 1,
        'z': 2,
        'center': 3,
        'xy': 4,
        'yz': 5,
        'xz': 6,
    }[axis]
    manip.set_active_handle(dispatch)
	def removeInfluenceMembership(self):
		
		# Check Context Status
		if mc.currentCtx() != self.context: return
		# Check UI Status
		if not mc.window('surfaceSkin_editMembershipToolUI',q=1,ex=1): return
		
		# Get surfaceSkin node
		surfaceSkinNode = mc.optionMenuGrp('ssEditInfMemberToolSurfaceSkin_OMG',q=1,v=1)
		# Get influence from list
		influence = mc.textScrollList('ssEditInfMemberToolInfluence_TSL',q=1,si=1)[0] # Get first selected item in list
		
		# Remove influence membership
		if type(self.dragComponentSelection) == list:
			componentList = glTools.utils.component.getComponentIndex(self.dragComponentSelection)
			for obj in componentList.keys():
				surfaceSkin_utilities().setSurfaceCoordArray(obj,componentList[obj],influence,surfaceSkinNode,mode=3)
예제 #33
0
def smoothFlood(skinCluster,iterations=1):
	'''
	Smooth flood all influences
	@param geometry: The geometry connected to the skinCluster to smooth
	@type geometry: str
	@param iterations: Number of smooth iterations
	@type iterations: int
	'''
	# Check zero iterations
	if not iterations: return
	
	# Get current tool
	currentTool = mc.currentCtx()
	
	# Select geometry
	geometry = glTools.utils.deformer.getAffectedGeometry(skinCluster).keys()
	mc.select(geometry)
	
	# Get skinCluster influence list
	influenceList = mc.skinCluster(skinCluster,q=True,inf=True)
	
	# Unlock influence weights
	for influence in influenceList: mc.setAttr(influence+'.lockInfluenceWeights',0)
	
	# Initialize paint context
	skinPaintTool = 'artAttrSkinContext'
	if not mc.artAttrSkinPaintCtx(skinPaintTool,ex=True):
		mc.artAttrSkinPaintCtx(skinPaintTool,i1='paintSkinWeights.xpm',whichTool='skinWeights')
	mc.setToolTo(skinPaintTool)
	mc.artAttrSkinPaintCtx(skinPaintTool,edit=True,sao='smooth')
	
	# Smooth Weights
	for i in range(iterations):
		print(skinCluster+': Smooth Iteration - '+str(i+1))
		for influence in influenceList:
			# Lock current influence weights
			mc.setAttr(influence+'.lockInfluenceWeights',1)
			# Smooth Flood
			mm.eval('artSkinSelectInfluence artAttrSkinPaintCtx "'+influence+'" "'+influence+'"')
			mc.artAttrSkinPaintCtx(skinPaintTool,e=True,clear=True)
			# Unlock current influence weights
			mc.setAttr(influence+'.lockInfluenceWeights',0)
	
	# Reset current tool
	mc.setToolTo(currentTool)
예제 #34
0
파일: tabPaint.py 프로젝트: leandropim/Tapp
    def updateHighlight(self,includeInfluence=True):
        '''
        updates highlight - if painting, adds  current influence to highlight
        '''
        if cmds.currentCtx()!=self.TOOL_PAINT:
            return

        if not LayerDataModel.getInstance().layerDataAvailable:
            return

        newHighlightItems = []
        if includeInfluence:
            currentInfluencePath = LayerDataModel.getInstance().mll.getPaintTargetPath();
            if currentInfluencePath:
                newHighlightItems.append(currentInfluencePath)
                
            
        SelectHelper.replaceHighlight(newHighlightItems)
예제 #35
0
    def updateHighlight(self, includeInfluence=True):
        '''
        updates highlight - if painting, adds  current influence to highlight
        '''
        if cmds.currentCtx() != self.TOOL_PAINT:
            return

        if not LayerDataModel.getInstance().layerDataAvailable:
            return

        newHighlightItems = []
        if includeInfluence:
            currentInfluencePath = LayerDataModel.getInstance(
            ).mll.getPaintTargetPath()
            if currentInfluencePath:
                newHighlightItems.append(currentInfluencePath)

        SelectHelper.replaceHighlight(newHighlightItems)
예제 #36
0
파일: tabPaint.py 프로젝트: jonntd/Tapp
    def updateHighlight(self, includeInfluence=True):
        '''
        updates highlight - if painting, adds  current influence to highlight
        '''
        if cmds.currentCtx() != self.TOOL_PAINT:
            return

        if not LayerDataModel.getInstance().layerDataAvailable:
            return

        newHighlightItems = []
        if includeInfluence:
            currentInfluence = cmds.ngSkinLayer(q=True, ci=True)
            # returns influence path, if current paint target has any
            if (len(currentInfluence) > 1):
                newHighlightItems.append(currentInfluence[1])

        SelectHelper.replaceHighlight(newHighlightItems)
예제 #37
0
파일: adpsa.py 프로젝트: nitinpeter/scripts
def setty(demod):
    sikk = mc.optionMenu('modi', q=1, sl=1)
    imax = mc.textField('nt_maxTF', q=1, tx=1)
    whichCtx = mc.currentCtx()
    whichCtx = whichCtx.replace('Context', 'Ctx')
    if whichCtx == 'artAttrSkinCtx' or whichCtx == 'artAttrCtx':
        if demod == 0:
            melons.eval("catch(`artAttrPaintOperation " + whichCtx +
                        " Replace`)")
        if demod == 1 or demod == 5:
            melons.eval("catch(`artAttrPaintOperation " + whichCtx +
                        " Smooth`)")
        if demod == 2:
            melons.eval("catch(`artAttrPaintOperation " + whichCtx + " Add`)")
        if demod == 3:
            melons.eval("catch(`artAttrPaintOperation " + whichCtx +
                        " Scale`)")
    sett(demod, sikk, imax)
예제 #38
0
    def updateHighlight(self,includeInfluence=True):
        '''
        updates highlight - if painting, adds  current influence to highlight
        '''
        if cmds.currentCtx()!=self.TOOL_PAINT:
            return

        if not LayerDataModel.getInstance().layerDataAvailable:
            return

        newHighlightItems = []
        if includeInfluence:
            currentInfluence = cmds.ngSkinLayer(q=True,ci=True)
            # returns influence path, if current paint target has any
            if (len(currentInfluence)>1):
                newHighlightItems.append(currentInfluence[1])
                
            
        SelectHelper.replaceHighlight(newHighlightItems)
예제 #39
0
 def switchTool(s, mesh=None):
     """
     Switch to our selection tool
     """
     s.lastTool = cmds.currentCtx()
     ### For testing, refresh the tool each time this is run!
     if cmds.draggerContext(s.tool, ex=True):
         cmds.deleteUI(s.tool)
     ###
     if mesh and mesh in s.meshes:
         s.setColour("%s.vtx[0:]" % mesh, (0.4,0.4,0.4)) # Highlight mesh if provided.
     cmds.draggerContext(
         s.tool,
         name=s.tool,
         releaseCommand=s.makeSelection,
         dragCommand=s.updateSelectionPreview, # Preview selection while dragging
         cursor="hand",
         image1="hands.png")
     cmds.setToolTo(s.tool)
     s.active = True
예제 #40
0
def switchInfluence():    
    sel = cmds.ls(sl = True)
    influenceList = cmds.skinCluster(sel, query = True, influence = True)
    unlockedList = []
    for num in influenceList:
        lockValue = cmds.getAttr('%s.liw'%num)
        if lockValue == False:
            unlockedList.append(num)
    #find selected influence
    currentCtx1 = cmds.currentCtx()
    currentInf = cmds.artAttrSkinPaintCtx(currentCtx1, query = True, inf = True)
    #Check for thing in index
    if currentInf in unlockedList:
        #find index
        index = unlockedList.index(currentInf)
    
        myJoint = unlockedList[(index -1)]
        mel.eval('artSkinSelectInfluence("artAttrSkinPaintCtx", "%s")'% myJoint)
    else:
        error("HappyBirthday Claytor")
예제 #41
0
파일: MMtoKey.py 프로젝트: liudger/May9
    def press_selected(self, menu, **mod):
        self._is_open_menu = False
        self._current_node = self.EMPTY_NODE
        self._cleanMenu()
        context = cmds.currentCtx()     # context marking menu
        cmds.contextInfo(context, title=True)
        cmds.popupMenu('MMtoKey_MMB', b=2, aob=True, mm=True, p=self._getPanel(), pmc=self._openMarkingMenu, **mod)
        if context in self.DATA_TOOL and self.DATA_TOOL[context].menu:
            mel.eval('source "menu_%s";' % self.DATA_TOOL[context].menu)
        elif self.pref_special_1:
            mel.eval('source "menu_%s";' % self.pref_special_1)

        # common menu
        cmds.popupMenu('MMtoKey_LMB', b=1, aob=True, mm=True, p=self._getPanel(), pmc=self._openMarkingMenu, **mod)
        if menu:
            mel.eval('source "menu_%s";' % menu)
            return
        self._current_node = self._findNode()
        if self._current_node.menu:
            mel.eval('source "menu_%s";' % self._current_node.menu)
        elif self.pref_special_0:
            mel.eval('source "menu_%s";' % self.pref_special_0)
def startDraw():
    sel = cmds.ls(sl=1, o=1)
    sel = sel[0]
    cmds.select(sel, r=True)

    mel.eval('MakePaintable;')
    vers = int(cmds.about(version=True))
    if not cmds.currentCtx() == 'dynWireCtx1':
        mainPath = mel.eval('getenv "MAYA_LOCATION"')
        if vers > 2016:
            brushLoc = mainPath + '/Examples/Paint_Effects/Pens/ballpointRough.mel'
        else:
            brushLoc = mainPath + '/brushes/pens/ballpointRough.mel'
        mel.eval('copyBrushToSelected "' + brushLoc + '"')

    cmds.select(cl=True)
    loc = cmds.toolPropertyWindow(q=True, loc=True)
    if loc:
        mel.eval('ToggleToolSettings;')

    cmds.scriptJob(event=['DagObjectCreated', 'ldmt_pfxToCurves()'],
                   compressUndo=True)
    cmds.scriptJob(event=['ToolChanged', 'ldmt_killPFXJob()'], runOnce=True)
	def hiliteMembers(self):
		
		# Check Context Status
		if mc.currentCtx() != self.context: return
		# Check UI Status
		if not mc.window('surfaceSkin_editMembershipToolUI',q=1,ex=1): return
		
		# Get surfaceSkin node
		surfaceSkinNode = mc.optionMenuGrp('ssEditInfMemberToolSurfaceSkin_OMG',q=1,v=1)
		# Get influence from list
		influence = mc.textScrollList('ssEditInfMemberToolInfluence_TSL',q=1,si=1)[0] # Get first selected item in list
		
		# Get affected geometry and components
		affectedGeo = surfaceSkin_utilities().getAffectedGeometry(surfaceSkinNode).keys()
		influenceMembers = surfaceSkin_utilities().getInfluenceMembership(influence,surfaceSkinNode,[],0)
		
		# Hilite component members
		if len(influenceMembers):
			for geo in affectedGeo: glTools.utils.selection.enableObjectVertexSelection(geo)
			mc.select(influenceMembers)

# Create Context Object (Global)
#ssEditInfluenceMembershipCTX = SurfaceSkinEditInfMembershipCTX('ssEditInfluenceMembershipCTX')
def loadTexture(fileName, fileType):
    if (fileName == None or len(fileName) == 0):
        return
    maya.mel.eval("PaintVertexColorTool;")
    context = cmds.currentCtx()
    cmds.artAttrPaintVertexCtx(context,
                               whichTool="colorPerVertex",
                               e=True,
                               ifm="rgba",
                               ifl=fileName)

    mesh = getMesh()

    if isMainColorSet():
        subColorSets = SUB_COLOR_SETS
        colors = mesh.getVertexColors(MAIN_COLOR_SET)
    else:
        subColorSets = [mesh.currentColorSetName()]
        colors = mesh.getVertexColors(subColorSets[0])

    # filter unused channel
    for subColorSet in subColorSets:
        mesh.setCurrentColorSetName(subColorSet)
        useR = int(subColorSet == R_CHANNEL or subColorSet == MAIN_COLOR_SET)
        useG = int(subColorSet == G_CHANNEL or subColorSet == MAIN_COLOR_SET)
        useB = int(subColorSet == B_CHANNEL or subColorSet == MAIN_COLOR_SET)
        useA = int(subColorSet == A_CHANNEL)

        numColors = len(colors)
        subColors = om.MColorArray(numColors, om.MColor((1.0, 1.0, 1.0, 1.0)))
        for i in xrange(numColors):
            color = colors[i]
            subColors[i] = om.MColor((color.r * useR + color.a * useA,
                                      color.g * useG + color.a * useA,
                                      color.b * useB + color.a * useA, 1))
        mesh.setVertexColors(subColors, getIncrementIter(numColors))
예제 #45
0
def getCurrentCtxName():
    ctx = cmds.currentCtx()
    className = ""
    if True == cmds.contextInfo(ctx, exists=True):
        className = cmds.contextInfo(ctx, c=True)
    return className
예제 #46
0
파일: tabPaint.py 프로젝트: leandropim/Tapp
 def isPainting(self):
     return cmds.currentCtx()==self.TOOL_PAINT
예제 #47
0
    def selection_changed(self, *args):
        """ make sure to opt out of the current spore tool when the selction
        is changed """

        if cmds.currentCtx().startswith('spore'):
            cmds.setToolTo('selectSuperContext')
예제 #48
0
def set_reference(mode=''):
    c_ctx = cmds.currentCtx(q=True)
    #print c_ctx
    sel = cmds.ls(sl=True, l=True)
    #print 'set reference :', mode, sel
    current_ctx = cmds.currentCtx()
    if mode == 'object':
        #print 'set reference object mode :'
        cmds.selectMode(o=True)
        rot = cmds.xform(sel, q=True, ro=True, ws=True)
        pos = cmds.xform(sel, q=True, t=True, ws=True)
        rx = rot[0] / 180 * math.pi
        ry = rot[1] / 180 * math.pi
        rz = rot[2] / 180 * math.pi
        cmds.manipScaleContext('Scale', e=True, orientAxes=(rx, ry, rz))
        cmds.manipRotateContext('Rotate', e=True, orientAxes=(rx, ry, rz))
        cmds.manipMoveContext('Move', e=True, orientAxes=(rx, ry, rz))

        cmds.setToolTo('scaleSuperContext')  #マニプ表示がおかしくなるのでいったんコンテキスト設定してから戻す
        cmds.setToolTo('RotateSuperContext')
        cmds.setToolTo('moveSuperContext')
        cmds.setToolTo(current_ctx)
    else:
        if mode == 'vertex':
            manip_type = 'PointHandleTowards'
            comp = cmds.polyListComponentConversion(sel, tv=True)
            comp = cmds.filterExpand(comp, sm=31)
            sel_node = '" , "'.join(pre_sel)
            #print 'vertex ref :', sel_node, comp[0]
        if mode == 'edge':
            manip_type = 'AlignHandleWith'
            comp = cmds.polyListComponentConversion(sel, te=True)
            comp = cmds.filterExpand(comp, sm=32)
            sel_node = comp[0]
        if mode == 'face':
            manip_type = 'AlignHandleWith'
            comp = cmds.polyListComponentConversion(sel, tf=True)
            comp = cmds.filterExpand(comp, sm=34)
            sel_node = comp[0]
        if comp:
            mel.eval('manipScaleOrient 5;')
            mel.eval('{  string $Selection1[]; $Selection1[0] = "' + comp[0] +
                     '"; manipScale' + manip_type + '($Selection1[0], {"' +
                     sel_node + '"}, {}, "", 0);;  };')
            mel.eval('manipRotateOrient 5;')
            mel.eval('{  string $Selection1[]; $Selection1[0] = "' + comp[0] +
                     '"; manipRotate' + manip_type + '($Selection1[0], {"' +
                     sel_node + '"}, {}, "", 0);;  };')
            mel.eval('manipMoveOrient 5;')
            mel.eval('{  string $Selection1[]; $Selection1[0] = "' + comp[0] +
                     '"; manipMove' + manip_type + '($Selection1[0], {"' +
                     sel_node + '"}, {}, "", 0);;  };')
        cmds.selectMode(co=True)
        if pre_ref_mode == 'vertex':
            cmds.selectType(pv=1,
                            smu=0,
                            smp=1,
                            pf=0,
                            pe=0,
                            smf=0,
                            sme=0,
                            puv=0)
        if pre_ref_mode == 'edge':
            cmds.selectType(pv=0,
                            smu=0,
                            smp=0,
                            pf=0,
                            pe=1,
                            smf=0,
                            sme=1,
                            puv=0)
        if pre_ref_mode == 'face':
            cmds.selectType(pv=0,
                            smu=0,
                            smp=0,
                            pf=1,
                            pe=0,
                            smf=0,
                            sme=1,
                            puv=0)
        trans = cmds.xform(sel, q=True, t=True, ws=True)
        num = len(trans) / 3
        x = y = z = 0
        for i in range(0, len(trans), 3):
            x += trans[i]
            y += trans[i + 1]
            z += trans[i + 2]
        pos = [x / num, y / num, z / num]
        #sel_obj = []
        #obj_list = list(set([vtx.split('.')[0] for vtx in pre_sel]))
        #if obj_list:
        #sel_obj = [cmds.listRelatives(s, p=True)[0] if cmds.nodeType(s)=='mesh' else s for s in obj_list]
        #print obj_list, pre_sel
        #cmds.hilite(obj_list, r=True)
        #cmds.hilite(pre_sel, r=True)
    #print 'set to pre mode :', pre_ref_mode
    #print 'set to mode pre :', pre_ref_mode
    if pre_ref_mode == 'object':
        cmds.selectMode(o=True)
    else:
        cmds.selectMode(co=True)
        if pre_obj_list:
            cmds.hilite(pre_obj_list, r=True)
    if pre_sel:
        cmds.select(pre_sel, r=True)
    else:
        cmds.select(cl=True)
    sb.after_pick_context(ctx=c_ctx)
    #移動マニプを選択の中心に移動する
    cmds.manipPivot(p=pos)
예제 #49
0
def get_matrix():
    global SYM_AVOIDANCE
    global sb
    from . import sisidebar_main as sb
    #print '-------------get Matrix---------------- :'
    #print 'select obj :', cmds.ls(sl=True)
    #current_tool = cmds.currentCtx()
    #print 'current tool ;',  current_tool
    #cmds.setToolTo('selectSuperContext')
    #cmds.setToolTo(current_tool)
    if SYM_AVOIDANCE:
        SYM_AVOIDANCE = False
        return
    #ロックの有無をチェック
    try:
        sb.window.attribute_lock_state(mode=3, check_only=True)
    except Exception as e:
        print e.message
        pass
    try:  #2018up2以降の不具合対応
        sid = sb.space_group.checkedId()
    except Exception as e:
        print e.message
        return
    #一旦スケールX値をリセットしてメインウィンドウクラスに変更をお知らせする
    #sb.set_temp_text('change')
    sb.set_active_mute()
    scale = ['', '', '']
    rot = ['', '', '']
    trans = ['', '', '']
    if cmds.selectMode(q=True, o=True):
        selection = cmds.ls(sl=True, type='transform')
        if selection:
            try:
                s_list, r_list, t_list = get_srt(selection)
            except Exception as e:
                print e.message
                return
            #print 'get matrix :', s_list, r_list, t_list
            for i in range(3):
                s_list = [
                    map(lambda a: round(float(a), view_decimal), xyz)
                    for xyz in s_list
                ]
                r_list = [
                    map(lambda a: round(float(a), view_decimal), xyz)
                    for xyz in r_list
                ]
                t_list = [
                    map(lambda a: round(float(a), view_decimal), xyz)
                    for xyz in t_list
                ]
                if not all(s[i] == s_list[0][i] for s in s_list):
                    #print 'not same'
                    scale[i] = ''
                else:
                    #print 'same'
                    scale[i] = str(s_list[0][i])
                if not all(r[i] == r_list[0][i] for r in r_list):
                    #print 'not same', r_list
                    rot[i] = ''
                else:
                    #print 'same', r_list
                    rot[i] = str(r_list[0][i])
                if not all(t[i] == t_list[0][i] for t in t_list):
                    trans[i] = ''
                else:
                    trans[i] = str(t_list[0][i])
        #sb.check_key_anim()
        if np_flag:
            sb.view_np_time(culc_time='- Numpy Calculation Mode -')
        else:
            sb.view_np_time(culc_time='- Usual Calculation Mode -')
    selection = cmds.ls(sl=True, type='float3')
    #カーブもとっておく
    cv_selection = cmds.ls(sl=True, type='double3', fl=True)
    #print cv_selection
    if selection or cv_selection:
        #ラティスポイント他すべてを有効にする
        sel_str = str(selection + cv_selection)
        '''
        if '.vtx[' in sel_str:
            cmds.selectType(polymeshVertex=True)
            #cmds.selectType(particle=True)
        '''
        if '.cv[' in sel_str:
            cmds.selectType(cv=True)
            cmds.selectMode(co=True)
        if '.pt[' in sel_str:
            cmds.selectType(latticePoint=True)
            cmds.selectMode(co=True)
        #オブジェクトモードでもコンポーネント選択がある場合は強制的にモード変更する

        components = cmds.polyListComponentConversion(selection,
                                                      tv=True) + cv_selection
        #print components
        #if not components:
        s_list, r_list, t_list = get_srt(components, mode='component')
        start = dt.datetime.now()  #計測開始
        #マニプ情報取得に必要な情報を集める
        sym = cmds.symmetricModelling(q=True, symmetry=True)
        current_tool = cmds.currentCtx()
        tools_list = [
            'scaleSuperContext', 'RotateSuperContext', 'moveSuperContext'
        ]
        if sym:
            axis_list = ['x', 'y', 'z']
            sym_axis = cmds.symmetricModelling(q=True, ax=True)
            axis_id = axis_list.index(sym_axis)
            meshes = cmds.ls(hl=True, l=True)
            #マニプが有効でない場合はシンメトリ座標を取得できないので自前計算
            if not current_tool in tools_list:
                for i, value in enumerate(t_list):
                    if i % 3 == axis_id:
                        value = math.sqrt(value**2)
                        t_list[i] = value

        if np_flag:
            #print 'culc in numpy'
            s_list = np.reshape(s_list, (len(s_list) / 3, 3))
            scale = np.average(s_list, axis=0).tolist()
            r_list = np.reshape(r_list, (len(r_list) / 3, 3))
            rot = np.average(r_list, axis=0).tolist()
            t_list = np.reshape(t_list, (len(t_list) / 3, 3))
            trans = np.average(t_list, axis=0).tolist()
        else:
            #print 'culc in math'
            srt_list = [0, 0, 0, 0, 0, 0, 0, 0, 0]
            for i in range(0, len(s_list), 3):
                srt_list[0] += s_list[i + 0]
                srt_list[1] += s_list[i + 1]
                srt_list[2] += s_list[i + 2]
            scale = map(lambda a: a / (len(s_list) / 3), srt_list[0:3])
            for i in range(0, len(r_list), 3):
                srt_list[3] += r_list[i + 0]
                srt_list[4] += r_list[i + 1]
                srt_list[5] += r_list[i + 2]
            rot = map(lambda a: a / (len(r_list) / 3), srt_list[3:6])
            for i in range(0, len(t_list), 3):
                srt_list[6] += t_list[i + 0]
                srt_list[7] += t_list[i + 1]
                srt_list[8] += t_list[i + 2]
            trans = map(lambda a: a / (len(t_list) / 3), srt_list[6:9])
        #シンメトリのときとワールド座標の場合の処理
        #ワールド空間のときもMayaのマニピュレータ位置とあわせる
        if sym or sid == 0 or sid == 4:
            if current_tool in tools_list:
                if current_tool == 'moveSuperContext':
                    trans = cmds.manipMoveContext('Move', q=True, p=True)
                elif current_tool == 'RotateSuperContext':
                    trans = cmds.manipRotateContext('Rotate', q=True, p=True)
                elif current_tool == 'scaleSuperContext':
                    trans = cmds.manipScaleContext('Scale', q=True, p=True)
                #ワールド空間でない且つ選択オブジェクトが1つの場合はマトリクス計算で座標を求める
                if sid != 0 and sid != 4 and len(meshes) == 1:
                    scale = cmds.xform(meshes[0], q=True, s=True, ws=True)
                    #scale = [1.0]*3
                    if len(meshes) == 1:
                        pos = trans + [1]  #行列掛けるようの位置配列、末尾に1つけとく
                        if np_flag:
                            #マトリクス計算で座標求める
                            matrix = cmds.xform(meshes[0],
                                                q=True,
                                                m=True,
                                                ws=True)
                            matrix = np.reshape(matrix, (4, 4))
                            rev_matrix = np.linalg.inv(matrix)  #逆行列
                            #print 'get mesh matrix :', matrix, meshes[0]
                            #print 'get rev matrix np:', rev_matrix
                            mul_matrix_trans = np.dot(pos, matrix)
                            mul_rev_matrix_trans = np.dot(pos, rev_matrix)
                            #print 'mul matrix :', mul_matrix_trans
                            #print 'mul rev matrix :', mul_rev_matrix_trans
                            trans = scale * mul_rev_matrix_trans[:3]
                            #print 'Local trans np:', trans
                        else:  #Numpy使わない処理
                            matrix = cmds.xform(meshes[0],
                                                q=True,
                                                m=True,
                                                ws=True)
                            rev_matrix = pm.ls(
                                meshes[0])[0].transformationMatrix().inverse()
                            #print 'get rev matrix :', rev_matrix
                            pos = [pos]  #行列掛けるようの位置配列、末尾に1つけとく
                            #print matrix
                            #print rev_matrix
                            mul_rev_matrix_trans = mm.dot(pos, rev_matrix)[0]
                            #print mul_rev_matrix_trans
                            trans = mm.mul(mul_rev_matrix_trans[:3], scale)
                        #print 'Local trans :', trans
                    #print 'sym pos :',  trans, meshes, sid
        #print 'trans :', trans
        end = dt.datetime.now()
        culc_time = end - start
        sb.view_np_time(culc_time='Culc Time ' + str(culc_time))
        #表示桁数を調整する
    try:
        scale = map(lambda a: round(float(a), view_decimal)
                    if a != '' else '', scale)
        rot = map(lambda a: round(float(a), view_decimal)
                  if a != '' else '', rot)
        trans = map(lambda a: round(float(a), view_decimal)
                    if a != '' else '', trans)
        #念のため0のマイナス符号を除去、main側のセットでもやってるんで一旦ミュート
        #print rot
        #scale = map(lambda a : float(str(a).replace('-0.0', '0.0')) if a=='-0.0' else a, scale)
        #rot = map(lambda a : float(str(a).replace('-0.0', '0.0')) if a=='-0.0' else a, rot)
        #trans = map(lambda a : float(str(a).replace('-0.0', '0.0')) if a=='-0.0' else a, trans)
        #print rot
        sb.set_pre_transform(trans, rot, scale)
        sb.set_srt_text(scale, rot, trans)
    except:
        sb.set_pre_transform(trans, rot, scale)
        sb.set_srt_text(scale, rot, trans)
예제 #50
0
파일: scene.py 프로젝트: ewerybody/melDrop
def stateToFileInfo():
    sel = m.ls(sl=1)
    selStr = '?'.join(sel)
    m.fileInfo('onSaveSelection',selStr)
    ctx = m.currentCtx()
    m.fileInfo('onSaveCtx',ctx)
예제 #51
0
 def create(self, *args):
     
     
     img = cmds.iconTextButton("TempCustomPivotBtn", query=True, image=True)
     onOff = (img[-10:-4] == "active")
     if onOff: 
         self.clear()
         cmds.select(self.sel)
         return
     
     cmds.undoInfo(openChunk=True)
     cmds.undoInfo(closeChunk=True)
     cmds.undoInfo(openChunk=True)
     cmds.undoInfo(closeChunk=True)
     cmds.undoInfo(openChunk=True)
     cmds.undoInfo(closeChunk=True)
     cmds.undoInfo(openChunk=True)
     
     self.clear()       
     
     
     getCurves  = animMod.getAnimCurves()
     animCurves = getCurves[0]
     getFrom    = getCurves[1] 
     
     if animCurves:        
         keyTimes            = animMod.getTarget("keyTimes", animCurves, getFrom)
           
     self.sel = cmds.ls(selection=True)
     if not self.sel: return
             
     cmds.iconTextButton("TempCustomPivotBtn", edit=True, image= uiMod.getImagePath("specialTools_create_temp_custom_pivot_active"),         highlightImage= uiMod.getImagePath("specialTools_create_temp_custom_pivot_active"))
    
     targetObj  = self.sel[-1]  
     aToolsMod.saveInfoWithScene(self.STORE_NODE, self.CTRLS, self.sel)
     
     currentFrame = cmds.currentTime(query=True) 
     aToolsMod.saveInfoWithScene(self.STORE_NODE, self.CURRENTFRAME, currentFrame)
     
     locators = []
     for loopSel in self.sel: 
         nameSpace       = utilMod.getNameSpace([loopSel])
         loopSelName     = "%s_%s"%(nameSpace[0][0], nameSpace[1][0])  
         locatorName     = "tempCustomPivot_%s"%loopSelName
         
         locator = animMod.createNull(locatorName)
         locators.append(locator)
     
         G.aToolsBar.align.align([locator], loopSel)
     
         
     locatorGroup = "tempCustomPivot_group"
     animMod.group(name=locatorGroup)        
     G.aToolsBar.align.align([locatorGroup], targetObj)
     with G.aToolsBar.createAToolsNode: cmds.parent(locators, locatorGroup)
     cmds.select(locatorGroup, replace=True)
     
     locators.append(locatorGroup)   
     
     aToolsMod.saveInfoWithScene(self.STORE_NODE, self.LOCATORS, locators)
  
     #parent ctrls to locator
     constraints = ["%s_tempCustomPivot_constraint"%loopConstraint for loopConstraint in self.sel]
     
     aToolsMod.saveInfoWithScene(self.STORE_NODE, self.CONSTRAINTS, constraints)
     
     for n, loopSel in enumerate(self.sel):
         with G.aToolsBar.createAToolsNode: cmds.parentConstraint(locators[n], loopSel, name=constraints[n], maintainOffset=True)
         constraintNode = "%s.blendParent1"%loopSel
         if not cmds.objExists(constraintNode): continue
         cmds.setKeyframe(constraintNode)
         if keyTimes:
             for loopTime in keyTimes[0]:
                 cmds.setKeyframe("%s.tx"%locatorGroup, time=(loopTime,loopTime))
                 if loopTime != currentFrame:
                     cmds.setKeyframe(constraintNode, time=(loopTime,loopTime), value=0)
     
     #enter edit mode
     cmds.setToolTo(cmds.currentCtx())
     cmds.ctxEditMode()
     
     #scriptjob    
     cmds.scriptJob(runOnce = True, killWithScene = True,  event =('SelectionChanged',  self.scriptJob_SelectionChanged))
예제 #52
0
 def isPainting(self):
     return cmds.currentCtx()==self.TOOL_PAINT