예제 #1
0
def _findCustomCreateCommand(nodeType):
    """
    Locate a custom command to create this nodeType, based on registered 
    custom classification categories. Return None if no match.
    """
    use2012 = not hasattr(cmds, 'callbacks')
    if use2012:
        # use the pre-2013 method of finding custom node create scripts
        return _findCustomCreateCommand2012(nodeType)

    # get the list of classifications which have custom handlers
    customClassifications = cmds.callbacks(hook='renderNodeClassification',
                                           executeCallbacks=True)
    if not customClassifications:
        return None
    for topclassif in customClassifications:
        if cmds.getClassification(nodeType, sat=topclassif):
            # this is a type with a custom handler
            postCmd = ''
            customCallbacks = cmds.callbacks(postCmd,
                                             nodeType,
                                             hook='createRenderNodeCommand',
                                             executeCallbacks=True)
            if customCallbacks and len(customCallbacks):
                # there should be only one callback, which must be a MEL fragment
                return customCallbacks[0]
예제 #2
0
def clearCallbacks():
    if cmds.about(batch=True):
        return
    try:
        cmds.callbacks(clearAllCallbacks=True, owner="arnold")
    except:
        pass
예제 #3
0
    def __init__(self, nodeName):
        """Generate the layout."""
        super(AEwalterStandinTemplate, self).__init__(nodeName)

        # self.hydraPluginsCombo = None

        self.beginScrollLayout()

        # We use "message" attribute to have access to the AE, but we don't
        # create an actual control. It should be before everything to save the
        # current node name before the controls access it.
        self.callCustom(self.__build, self.__replace, "message")

        # The main layout.
        self.beginLayout("Walter", collapse=False)

        # Walter toolbar
        self.callCustom(self.__toolbarNew, self.__toolbarReplace, "dummy")

        # Walter Layers widget
        self.callCustom(self.__layersNew, self.__layersReplace,
                        "cacheFileName")

        self.endLayout()

        # Ability to add custom layouts from external plugins.
        cmds.callbacks(nodeName,
                       executeCallbacks=True,
                       hook="AETemplateCustomContent")

        # Put all the rest to the separate layout.
        self.addExtraControls()

        self.endScrollLayout()
    def __init__(self, nodeName):
        """Generate the layout."""
        super(AEwalterOverrideTemplate, self).__init__(nodeName)

        # Don't do anything if it's not the attribute editor.
        if int(cmds.about(v=True)) <= 2016 and \
           not cmds.setParent(query=True).startswith('Maya'):
            return

        if int(cmds.about(v=True)) >= 2018 and \
           not cmds.setParent(query=True).startswith('AttributeEditor'):
            return

        self.beginScrollLayout()

        # The main layout.
        self.beginLayout("Walter", collapse=False)

        group = None

        # Create all the attributes
        for attr in ATTRIBUTES:
            currentGroup = attr.get('group')

            # Greate a group
            if currentGroup != group:
                if group:
                    self.endLayout()
                if currentGroup:
                    self.beginLayout(currentGroup, collapse=False)
                group = currentGroup

            self.callCustom(
                self.attributeBuild,
                self.attributeReplace,
                attr['name'])

        if group:
            self.endLayout()

        # Create a context menu. We use "message" attribute to have access to
        # the AE, but we don't create an actual control.
        # It's here to be called after all the UI items are created because we
        # we need everything built when we hide and show the layouts.
        self.callCustom(self.build, self.replace, "message")

        self.endLayout()

        # Ability to add custom layouts from external plugins.
        cmds.callbacks(
            nodeName,
            executeCallbacks=True,
            hook="AETemplateCustomContent")

        # Put all the rest to the separate layout.
        self.addExtraControls()

        self.endScrollLayout()
예제 #5
0
    def __init__(self):
        super(RenderSetup, self).__init__()
        self.activeLayerChangeObservable = observable.Observable()
        self._cbIds = []
        self.visibleLayerBeforeUnloadReference = None
        self.visibleLayerBeforeLoadReference = None
        self._addToModelCbId = None

        self._callbacks = {
            sceneObservable.SceneObservable.NODE_ADDED:
            self._onMayaNodeAddedCB,
            sceneObservable.SceneObservable.BEFORE_REFERENCE_LOAD:
            self._beforeLoadReferenceCB,
            sceneObservable.SceneObservable.REFERENCE_LOADED:
            self._afterLoadReferenceCB,
            sceneObservable.SceneObservable.BEFORE_REFERENCE_UNLOAD:
            self._beforeUnloadReferenceCB,
            sceneObservable.SceneObservable.REFERENCE_UNLOADED:
            self._afterUnloadReferenceCB
        }

        for type, callback in self._callbacks.iteritems():
            sceneObservable.instance().register(type, callback)

        self._cbIds.append(
            OpenMaya.MDGMessage.addNodeRemovedCallback(self._onNodeRemoved,
                                                       self.kTypeName))

        self._cbIds.append(
            OpenMaya.MSceneMessage.addCallback(
                OpenMaya.MSceneMessage.kBeforeSave, self._beforeSaveSceneCB))

        self._cbIds.append(
            OpenMaya.MSceneMessage.addCallback(
                OpenMaya.MSceneMessage.kAfterOpen, self._afterOpenCB))

        # List to keep objects created by duplication.
        # This allows objects to be added only once to the default collection of the visible layer
        # when duplication is completed.
        self._duplicated = None
        self._cbIds.append(
            OpenMaya.MModelMessage.addBeforeDuplicateCallback(
                self._beforeDuplicate))
        self._cbIds.append(
            OpenMaya.MModelMessage.addAfterDuplicateCallback(
                self._afterDuplicate))

        self._defaultRenderLayer = renderLayer.DefaultRenderLayer()

        # Add a callback to prevent nodes to be deleted when Scene Cleanup is executed
        if not cmds.about(batch=True):
            cmds.callbacks(
                addCallback=_preventDeletionFromSceneCleanupCB,
                hook="preventMaterialDeletionFromCleanUpSceneCommand",
                owner="renderSetup")
예제 #6
0
        def prepare_arnold_shader(self):
            # load plugin
            if not cmds.pluginInfo('mtoa', q=True, l=True):
                cmds.loadPlugin('mtoa')
            if cmds.getAttr("defaultRenderGlobals.ren") != 'arnold':
                cmds.setAttr('defaultRenderGlobals.ren', 'arnold', type='string')
            cmds.callbacks(executeCallbacks=True, hook='updateMayaRenderingPreferences')

            # convert mari attr names to arnold attr names
            converted_attrs = mgo_convert.AiStandard(self.sd['attributes'], reverse=True)
            for attr in converted_attrs:
                self.sd['attributes'][attr[0]] = attr[1]
예제 #7
0
 def dispose(self):
     self.clearAll()
     # remove all callbacks that have been registered
     for id in self._cbIds:
         OpenMaya.MMessage.removeCallback(id)
     for type, callback in self._callbacks.iteritems():
         sceneObservable.instance().unregister(type, callback)
     self._cbIds = []
     if not cmds.about(batch=True):
         cmds.callbacks(
             removeCallback=_preventDeletionFromSceneCleanupCB,
             hook="preventMaterialDeletionFromCleanUpSceneCommand",
             owner="renderSetup")
예제 #8
0
def registerHypershade ():
    hypershadeCallbacks = [("hyperShadePanelBuildCreateMenu",       hyperShadePanelBuildCreateMenuCallback),
                           ("hyperShadePanelBuildCreateSubMenu",    hyperShadePanelBuildCreateSubMenuCallback),
                           ("hyperShadePanelPluginChange",          hyperShadePanelPluginChangeCallback),
                           #("createRenderNodeSelectNodeCategories", createRenderNodeSelectNodeCategoriesCallback),
                           ("createRenderNodePluginChange",         createRenderNodePluginChangeCallback),
                           ("renderNodeClassification",             renderNodeClassificationCallback),
                           ("createRenderNodeCommand",              createRenderNodeCommandCallback),
                           ("nodeCanBeUsedAsMaterial",              nodeCanBeUsedAsMaterialCallback),
                           ("buildRenderNodeTreeListerContent",     buildRenderNodeTreeListerContentCallback) ]

    # Add callbacks
    for hook, callback in hypershadeCallbacks:
        mc.callbacks (addCallback = callback, hook = hook, owner = "niepce")
예제 #9
0
def uninitialize(mplugin):

    for m in _initializeModules:
        m.uninitialize()

    cmds.callbacks(removeCallback=addRenderSetupPreferences,
                   hook='addMayaRenderingPreferences',
                   owner='renderSetup')

    for cmd in commands:
        try:
            mplugin.deregisterCommand(cmd.kCmdName)
        except:
            OpenMaya.MGlobal.displayError('Unregister failed for %s' %
                                          cmd.kCmdName)
예제 #10
0
 def _getNewConnections(surfaceShader, shadingEngine):
     """ Get a list for connections that should be made when connecting a 
     surface shader to a shading engine. This can be customizable by plug-ins
     using the callback hook 'provideNodeToNodeConnection'. """
     connections = []
     fnSurfaceShader = OpenMaya.MFnDependencyNode(surfaceShader)
     fnShadingEngine = OpenMaya.MFnDependencyNode(shadingEngine)
     # Check if a plug-in has provided custom attributes to use for the connection
     # Using EAFP style code and catch any exception raised if no custom attributes
     # are given, or they are given in incorrect format.
     try:
         result = cmds.callbacks(fnSurfaceShader.typeName,
                                 fnShadingEngine.typeName,
                                 executeCallbacks=True,
                                 hook='provideNodeToNodeConnection')
         attributes = result[0].split(':')
         # Make a connection for each pair of "src:dst" attributes
         count = len(attributes)
         for i in xrange(0, count, 2):
             shaderPlug = fnSurfaceShader.findPlug(attributes[i], False)
             enginePlug = fnShadingEngine.findPlug(attributes[i + 1], False)
             connections.append((shaderPlug, enginePlug))
     except:
         # Fall back to default behavior making a default connection
         # between surface shader and shading engine
         shaderPlug = fnSurfaceShader.findPlug('outColor', False)
         enginePlug = fnShadingEngine.findPlug('surfaceShader', False)
         if shaderPlug and enginePlug:
             connections.append((shaderPlug, enginePlug))
     return connections
예제 #11
0
        def prepare_arnold_shader(self):
            # load plugin
            if not cmds.pluginInfo('mtoa', q=True, l=True):
                cmds.loadPlugin('mtoa')
            if cmds.getAttr("defaultRenderGlobals.ren") != 'arnold':
                cmds.setAttr('defaultRenderGlobals.ren',
                             'arnold',
                             type='string')
            cmds.callbacks(executeCallbacks=True,
                           hook='updateMayaRenderingPreferences')

            # convert mari attr names to arnold attr names
            converted_attrs = mgo_convert.AiStandard(self.sd['attributes'],
                                                     reverse=True)
            for attr in converted_attrs:
                self.sd['attributes'][attr[0]] = attr[1]
예제 #12
0
def initialize(mplugin):

    mel.eval('source \"renderSetupImportExportCallbacks.mel\"')

    cmds.callbacks(addCallback=addRenderSetupPreferences,
                   hook='addMayaRenderingPreferences',
                   owner='renderSetup')

    for cmd in commands:
        try:
            mplugin.registerCommand(cmd.kCmdName,
                                    cmd.creator,
                                    createSyntaxFunc=cmd.createSyntax)
        except:
            OpenMaya.MGlobal.displayError('Register failed for %s' %
                                          cmd.kCmdName)

    for m in _initializeModules:
        m.initialize()
예제 #13
0
파일: language.py 프로젝트: zewt/pymel
def callbacks(*args, **kwargs):
    if len(args):
        doPassSelf = kwargs.pop('passSelf', False)
    else:
        doPassSelf = False
    for key in ['ac', 'addCallback', 'rc', 'removeCallback']:
        try:
            cb = kwargs[key]
            if callable(cb):
                kwargs[key] = _factories.makeUICallback(cb, args, doPassSelf)
        except KeyError:
            pass
    res = cmds.callbacks(*args, **kwargs)
    return res
예제 #14
0
def listUnusedShadingNodes(verbose=False):
    """
    List all Unused Shading Nodes
    @param verbose: Print progress messages
    @type verbose: bool
    """
    # List Unused Shading Nodes
    unused = []

    # ==============
    # - Check Sets -
    # ==============

    # Check Unused Sets
    for curr_set in cmds.ls(sets=True):

        # Skip Default Sets
        if curr_set.count('default'):
            continue

        # Check Set is Used
        if shadingGroupUnused(curr_set):
            if verbose: print('Unused shading group: ' + curr_set)
            unused.append(curr_set)

    # ===================
    # - Check Materials -
    # ===================

    # Delete all unconnected materials.
    materials = cmds.ls(long=True, mat=True)

    for currShader in materials:

        # Skip Default Materials
        if currShader.count('default'): continue

        # Skip Defaults
        if currShader == 'lambert1': continue
        if currShader == 'particleCloud1': continue

        shouldDelete = False

        # conn is an array of plug/connection pairs
        conn = cmds.listConnections(currShader,
                                    shapes=True,
                                    connections=True,
                                    source=False)

        # Check Shader Connections
        for j in range(0, len(conn), 2):

            # Check connection to unused shading engine
            se = cmds.listConnections(conn[j], type='shadingEngine')
            if not se:
                se = []
            else:
                if unused.count(se[0]):
                    shouldDelete = True
                    break

            # Check Message Connection
            if conn[j] != (currShader + '.message'):
                shouldDelete = False
                break

            # Third Party Prevent Deletions
            thirdPartyPreventDeletions = cmds.callbacks(
                currShader,
                conn[j + 1],
                conn[j],
                executeCallbacks=True,
                hook="preventMaterialDeletionFrocmdsleanUpSceneCommand")
            if not thirdPartyPreventDeletions: thirdPartyPreventDeletions = []
            thirdPartyPreventsDeletion = False
            for deletionPrevented in thirdPartyPreventDeletions:
                if (deletionPrevented):
                    thirdPartyPreventsDeletion = True
                    break

            # Check if Used
            if se:
                shouldDelete = False
                break
            elif thirdPartyPreventsDeletion:
                shouldDelete = False
                break
            else:
                shouldDelete = True

        if shouldDelete:
            if verbose: print('Unused shader: ' + currShader)
            unused.append(currShader)

    # =======================
    # - Check Shading Utils -
    # =======================

    # Get All Render Nodes
    allRenderNodes = getRenderNodes()

    for node in allRenderNodes:

        # Skip Default Nodes
        if node.count('default'): continue

        # Skip Defaults
        if node == 'lambert1': continue
        if node == 'particleCloud1': continue

        # Deleting one node can delete other connected nodes.
        if not cmds.objExists(node): continue

        # Check heightField
        if cmds.nodeType(node) == 'heightField':
            conn = cmds.listConnections(node,
                                        connections=True,
                                        source=True,
                                        shapes=True)
            if conn: continue

        # It's a texture, postprocess or utility node. Now determine if the readable connections are done.
        shouldDelete = True

        # Decide whether or not the node is unused
        conn = cmds.listConnections(node, c=True, s=False, shapes=True) or []
        for j in range(0, len(conn), 2):

            # Check Messgae Connection
            if conn[j].count('.message'):
                connType = cmds.nodeType(conn[j + 1])
                connList = [
                    'shadingEngine', 'imagePlane', 'arrayMapper',
                    'directionalLight', 'spotLight', 'pointLight', 'areaLight',
                    'transform'
                ]

                if connList.count(connType):
                    shouldDelete = False

                if cmds.objectType(conn[j + 1], isa='camera') == connType:
                    shouldDelete = False

                # Check Classification
                if shouldDelete and mel.eval('isClassified "' + conn[j + 1] +
                                             '" "shader/surface"'):
                    shouldDelete = False
                if shouldDelete and mel.eval('isClassified "' + conn[j + 1] +
                                             '" "shader/volume"'):
                    shouldDelete = False
                if shouldDelete and mel.eval('isClassified "' + conn[j + 1] +
                                             '" "shader/displacement"'):
                    shouldDelete = False

                # Give plugins a chance to label the node as 'shouldnt be deleted'
                thirdPartyPreventDeletions = cmds.callbacks(
                    node,
                    conn[j + 1],
                    conn[j],
                    executeCallbacks=True,
                    hook='preventMaterialDeletionFrocmdsleanUpSceneCommand')
                if not thirdPartyPreventDeletions:
                    thirdPartyPreventDeletions = []
                # thirdPartyPreventDeletions = cmds.callbacks( -executeCallbacks -hook "preventMaterialDeletionFrocmdsleanUpSceneCommand" $node $conn[$j+1] $conn[$j]`;

                for deletionPrevented in thirdPartyPreventDeletions:
                    if deletionPrevented:
                        shouldDelete = False
                        break

                if not shouldDelete: break

            else:
                shouldDelete = False
                break

        if shouldDelete:
            if verbose: print('Unused render node: ' + node)
            unused.append(node)

    # =================
    # - Return Result -
    # =================

    return unused
예제 #15
0
def listUnusedShadingNodes(verbose=False):
    """
    List all Unused Shading Nodes
    @param verbose: Print progress messages
    @type verbose: bool
    """
    # List Unused Shading Nodes
    unused = []

    # ==============
    # - Check Sets -
    # ==============

    # Check Unused Sets
    for curr_set in cmds.ls(sets=True):

        # Skip Default Sets
        if curr_set.count('default'):
            continue

        # Check Set is Used
        if shadingGroupUnused(curr_set):
            if verbose: print('Unused shading group: ' + curr_set)
            unused.append(curr_set)

    # ===================
    # - Check Materials -
    # ===================

    # Delete all unconnected materials.
    materials = cmds.ls(long=True, mat=True)

    for currShader in materials:

        # Skip Default Materials
        if currShader.count('default'): continue

        # Skip Defaults
        if currShader == 'lambert1': continue
        if currShader == 'particleCloud1': continue

        shouldDelete = False

        # conn is an array of plug/connection pairs
        conn = cmds.listConnections(currShader, shapes=True, connections=True, source=False)

        # Check Shader Connections
        for j in range(0, len(conn), 2):

            # Check connection to unused shading engine
            se = cmds.listConnections(conn[j], type='shadingEngine')
            if not se:
                se = []
            else:
                if unused.count(se[0]):
                    shouldDelete = True
                    break

            # Check Message Connection
            if conn[j] != (currShader + '.message'):
                shouldDelete = False
                break

            # Third Party Prevent Deletions
            thirdPartyPreventDeletions = cmds.callbacks(currShader, conn[j + 1], conn[j], executeCallbacks=True,
                                                      hook="preventMaterialDeletionFrocmdsleanUpSceneCommand")
            if not thirdPartyPreventDeletions: thirdPartyPreventDeletions = []
            thirdPartyPreventsDeletion = False
            for deletionPrevented in thirdPartyPreventDeletions:
                if (deletionPrevented):
                    thirdPartyPreventsDeletion = True
                    break

            # Check if Used
            if se:
                shouldDelete = False
                break
            elif thirdPartyPreventsDeletion:
                shouldDelete = False
                break
            else:
                shouldDelete = True

        if shouldDelete:
            if verbose: print('Unused shader: ' + currShader)
            unused.append(currShader)

    # =======================
    # - Check Shading Utils -
    # =======================

    # Get All Render Nodes
    allRenderNodes = getRenderNodes()

    for node in allRenderNodes:

        # Skip Default Nodes
        if node.count('default'): continue

        # Skip Defaults
        if node == 'lambert1': continue
        if node == 'particleCloud1': continue

        # Deleting one node can delete other connected nodes.
        if not cmds.objExists(node): continue

        # Check heightField
        if cmds.nodeType(node) == 'heightField':
            conn = cmds.listConnections(node, connections=True, source=True, shapes=True)
            if conn: continue

        # It's a texture, postprocess or utility node. Now determine if the readable connections are done.
        shouldDelete = True

        # Decide whether or not the node is unused
        conn = cmds.listConnections(node, c=True, s=False, shapes=True) or []
        for j in range(0, len(conn), 2):

            # Check Messgae Connection
            if conn[j].count('.message'):
                connType = cmds.nodeType(conn[j + 1])
                connList = ['shadingEngine',
                            'imagePlane',
                            'arrayMapper',
                            'directionalLight',
                            'spotLight',
                            'pointLight',
                            'areaLight',
                            'transform']

                if connList.count(connType):
                    shouldDelete = False

                if cmds.objectType(conn[j + 1], isa='camera') == connType:
                    shouldDelete = False

                # Check Classification
                if shouldDelete and mel.eval('isClassified "' + conn[j + 1] + '" "shader/surface"'):
                    shouldDelete = False
                if shouldDelete and mel.eval('isClassified "' + conn[j + 1] + '" "shader/volume"'):
                    shouldDelete = False
                if shouldDelete and mel.eval('isClassified "' + conn[j + 1] + '" "shader/displacement"'):
                    shouldDelete = False

                # Give plugins a chance to label the node as 'shouldnt be deleted'
                thirdPartyPreventDeletions = cmds.callbacks(node, conn[j + 1], conn[j], executeCallbacks=True,
                                                          hook='preventMaterialDeletionFrocmdsleanUpSceneCommand')
                if not thirdPartyPreventDeletions: thirdPartyPreventDeletions = []
                # thirdPartyPreventDeletions = cmds.callbacks( -executeCallbacks -hook "preventMaterialDeletionFrocmdsleanUpSceneCommand" $node $conn[$j+1] $conn[$j]`;

                for deletionPrevented in thirdPartyPreventDeletions:
                    if deletionPrevented:
                        shouldDelete = False
                        break

                if not shouldDelete: break

            else:
                shouldDelete = False
                break

        if shouldDelete:
            if verbose: print('Unused render node: ' + node)
            unused.append(node)

    # =================
    # - Return Result -
    # =================

    return unused
예제 #16
0
def registerCallbacks():
    if cmds.about(batch=True):
        return
        
    
        
    cmds.callbacks(addCallback=aiHyperShadePanelBuildCreateMenuCallback,
                   hook="hyperShadePanelBuildCreateMenu",
                   owner="arnold")

    cmds.callbacks(addCallback=aiHyperShadePanelBuildCreateSubMenuCallback,
                   hook="hyperShadePanelBuildCreateSubMenu",
                   owner="arnold")

    cmds.callbacks(addCallback=aiCreateRenderNodeSelectNodeCategoriesCallback,
                   hook="createRenderNodeSelectNodeCategories",
                   owner="arnold")
               

    # FIXME: Maya doc is wrong
    #cmds.callbacks(addCallback=aiRenderNodeClassificationCallback,
    #               hook="addToRenderNodeTreeLister",
    #              owner="arnold")
    # Should be this instead

    cmds.callbacks(addCallback=aiRenderNodeClassificationCallback,
                   hook="renderNodeClassification",
                   owner="arnold")

    cmds.callbacks(addCallback=aiBuildRenderNodeTreeListerContentCallback,
                   hook="buildRenderNodeTreeListerContent",
                   owner="arnold")

    cmds.callbacks(addCallback=aiCreateRenderNodePluginChangeCallback,
                   hook="createRenderNodePluginChange",
                   owner="arnold")

    cmds.callbacks(addCallback=templates.loadArnoldTemplate,
                   hook="AETemplateCustomContent",
                   owner="arnold")

    cmds.callbacks(addCallback=aiProvideClassificationStringsForFilteredTreeListerCallback,
                   hook="provideClassificationStringsForFilteredTreeLister",
                   owner="arnold")

    cmds.callbacks(addCallback=aiNodeCanBeUsedAsMaterialCallback,
                   hook="nodeCanBeUsedAsMaterial",
                   owner="arnold")
예제 #17
0
from Cube import Cube
from PyMaya import rgb
import maya.cmds as cmds
from random import *
import math

screenObjects = cmds.ls("pCube*", "blinn*")
cmds.callbacks(clearAllCallbacks=True)
if (len(screenObjects) > 0): cmds.delete(screenObjects)


def getDataFromFile(fileName):
    with open(fileName, 'r') as f:
        data = eval(f.read())
    return data


def animateNotes():
    depthMap = getDataFromFile(
        '/Volumes/Users/cmgeorge/documents/depthData.txt')
    imageData = getDataFromFile('/Volumes/Users/cmgeorge/documents/garage.txt')
    imageRows = len(imageData)
    imageCols = len(imageData[0])
    depthRows = len(depthMap)
    depthCols = len(depthMap[0])
    rowScaling = depthRows / float(imageRows)
    colScaling = depthCols / float(imageCols)
    top = imageRows * .25
    for r in range(imageRows):
        for c in range(imageCols):
            pix = imageData[r][c]