示例#1
0
def createMasterBlocker(name='BlockerGroup',
                        parent=NodegraphAPI.GetRootNode()):
    rootNode = parent
    #create the groupNode
    groupNode = NodegraphAPI.CreateNode('Group', rootNode)
    groupNode.setName(name)
    #add in and out port
    groupNode.addInputPort('in')
    groupNode.addOutputPort('out')
    #add attribute to switch the display of group node to normal node
    groupNodeAttrDict = {'ns_basicDisplay': 1, 'ns_iconName': ''}
    groupNode.setAttributes(groupNodeAttrDict)
    blockerName = 'Blocker1'

    #create a first blocker
    blocker = createSingleBlocker(groupNode, 'getParent().getParent().', False)
    paramui(groupNode, blocker.getName(), True)

    #reorder the button addBlocker to be the last param
    blockerParam = groupNode.getParameters()
    paramAddBlocker = blockerParam.getChild('addBlocker')
    numberOfChild = blockerParam.getNumChildren() - 1
    blockerParam.reorderChild(paramAddBlocker, numberOfChild)

    #create a dot node
    dotNode = NodegraphAPI.CreateNode('Dot', groupNode)
    dotNode.setName('outDot')

    #connection
    sendGroup = groupNode.getSendPort('in')
    returnGroup = groupNode.getReturnPort('out')
    blocker.getInputPort('in').connect(sendGroup)
    blocker.getOutputPort('out').connect(dotNode.getInputPort('input'))
    dotNode.getOutputPort('output').connect(returnGroup)

    #set position of nodes
    centralPos = NodegraphAPI.GetNodePosition(blocker)
    NodegraphAPI.SetNodePosition(dotNode, (centralPos[0], centralPos[1] - 50))

    #put the node under the mouse
    currentSelection = NodegraphAPI.GetAllSelectedNodes()
    for node in currentSelection:
        NodegraphAPI.SetNodeSelected(node, False)
    NodegraphAPI.SetNodeSelected(groupNode, True)
    # Get list of selected nodes
    nodeList = NodegraphAPI.GetAllSelectedNodes()
    # Find Nodegraph tab and float nodes
    nodegraphTab = UI4.App.Tabs.FindTopTab('Node Graph')
    if nodegraphTab:
        nodegraphTab.floatNodes(nodeList)
示例#2
0
def setParameters(parameter_name_value_pair, node=[], time=0.0):
    '''
    set the given parameter and value on the selected(or given) node
    input parameter name and value should be a dict: {parameter_name:[value, time]}
    return parameters list
    '''
    if not node:
        sel = NodegraphAPI.GetAllSelectedNodes()
    else:
        sel = node
        if not isinstance(sel, list):
            sel = [sel]
    collections = []
    for s in sel:
        #get the parameter objects
        params = traverseParameterGroup(s.getParameters())
        for p in params:
            for (n, v) in parameter_name_value_pair.iteritems():
                if p.getFullName().lower().endswith(n.lower()):
                    if p.getType() == 'group':
                        continue
                    p.setUseNodeDefault(False)
                    if type(v) in [float, long, int, str, tuple]:
                        p.setValue(v, time)
                        print p.getFullName() + ': ' + str(
                            v) + ' at time ' + str(time)
                    else:
                        p.setValue(v[0], v[1])
                        print p.getFullName() + ': ' + str(
                            v[0]) + ' at time ' + str(v[1])
                    collections.append(p)
    collections = list(set(collections))
    return collections
示例#3
0
 def doIt(self):
     node = NodegraphAPI.GetAllSelectedNodes()
     lenNode = len(node)
     if lenNode < 1 or lenNode > 1:
         self.messageBox = QMessageBox()
         self.messageBox.setIcon(QMessageBox.Warning)
         self.messageBox.setText("Please choose a single node")
         self.messageBox.setStandardButtons(QMessageBox.Ok)
         self.messageBox.exec_()
     else :
         createKatanaNodes()
         self.close()
示例#4
0
def set_knode_disable(knodes=None):
    '''
    :description set the k node disable(bypassed true)
    :param knode <list>
    :example
        from core import nodegraph
        nodegraph.set_knode_disable()
    '''
    if not knodes:
        knodes = NodegraphAPI.GetAllSelectedNodes()
    for knode in knodes:
        knode.setBypassed(True)
示例#5
0
def get_scene_selected_nodes():
    '''
    :description get all selected nodes from the scene
    :example
        from core import nodegraph
        nodegraph.get_scene_selected_nodes()
    '''
    knodes = NodegraphAPI.GetAllSelectedNodes()
    nodes = []
    for knode in knodes:
        nodes.append(knode.getName())
    return nodes
示例#6
0
def set_knode_unlocked(knodes=None):
    '''
    :description set the k node locked
    :param knodes <list>
    :example
        from core import nodegraph
        nodegraph.set_knode_locked()
    '''
    if not knodes:
        knodes = NodegraphAPI.GetAllSelectedNodes()
    for knode in knodes:
        knode.setLocked(False)
示例#7
0
    def _set_select_node(self, eventType=None, eventID=None, node=None):

        msg = []
        self.selected_nodes = []

        nodes = NodegraphAPI.GetAllSelectedNodes()
        for node in nodes:
            if node.getType() == "Render":
                msg.append(node.getName())
                self.selected_nodes.append(node)
        msg = ",".join(msg)
        self.ui.sel_node.setText(msg)
        return
示例#8
0
 def displayOpenDialog(self):
     fname = str(
         QFileDialog.getOpenFileName(self, 'Open file',
                                     '/s/prodanim/asterix2',
                                     "Katana files (*.katana)"))
     if fname == '':
         print 'No file has been open'
     if self.sender().objectName() == 'openAction':
         KatanaFile.Load(fname)
         print 'Loading : ' + fname
     else:
         currentSelection = NodegraphAPI.GetAllSelectedNodes()
         #deselect all the node to select only the 2 created nodes and put them floating under the mouse
         for node in currentSelection:
             NodegraphAPI.SetNodeSelected(node, False)
         KatanaFile.Import(fname, floatNodes=True)
         print 'importing : ' + fname
         nodeList = NodegraphAPI.GetAllSelectedNodes()
         # Find Nodegraph tab and float nodes
         nodegraphTab = Tabs.FindTopTab('Node Graph')
         if nodegraphTab:
             nodegraphTab.floatNodes(nodeList)
示例#9
0
def createMasterSample(name='SampleGroup',parent = NodegraphAPI.GetRootNode()):
    rootNode = parent
    #create the groupNode
    groupNode = NodegraphAPI.CreateNode('Group',rootNode)
    groupNode.setName(name)
    #add in and out port
    groupNode.addInputPort('in')
    groupNode.addOutputPort('out')
    #add attribute to switch the display of group node to normal node
    groupNodeAttrDict = {'ns_basicDisplay': 1,'ns_iconName': ''}
    groupNode.setAttributes(groupNodeAttrDict)
    blockerName = 'Blocker1'

    addButton =groupNode.getParameters().createChildString('addSampleNode','add sample node')
    addButton.setHintString("{'widget': 'scriptButton', 'buttonText': 'add Sample Node', 'scriptText': \"from sampleGroupCreate import displayLineUI\\n"
                                    "a=displayLineUI(node)\\na.show()\", 'help': 'add a new sample block to the group'}")

    #create a dot node
    dotOutNode = NodegraphAPI.CreateNode('Dot',groupNode)
    dotOutNode.setName('outDot')

    #connection
    sendGroup = groupNode.getSendPort('in')
    returnGroup = groupNode.getReturnPort('out')
    dotOutNode.getInputPort('input').connect(sendGroup)
    dotOutNode.getOutputPort('output').connect(returnGroup)

    #put the node under the mouse
    currentSelection = NodegraphAPI.GetAllSelectedNodes()
    for node in currentSelection:
        NodegraphAPI.SetNodeSelected(node,False)
    NodegraphAPI.SetNodeSelected(groupNode,True)
    # Get list of selected nodes
    nodeList = NodegraphAPI.GetAllSelectedNodes()
    # Find Nodegraph tab and float nodes
    nodegraphTab = UI4.App.Tabs.FindTopTab('Node Graph')
    if nodegraphTab:
        nodegraphTab.floatNodes(nodeList)
示例#10
0
    def __getScopedNodes(self):

        nodes = self.__getAllShadingNetworkNodes()

        if str(self.__scopePopup.currentText()).startswith('Upstream'):
            snmNodeName = str(
                self.__shadingNetworkMaterialsPopup.currentText())
            if not snmNodeName:
                return []

            snmNode = NodegraphAPI.GetNode(snmNodeName)
            if not snmNode:
                raise RuntimeError, "Unable to find the node '%s'" % snmNodeName

            upstreamSet = set(
                NodegraphAPI.Util.GetAllConnectedInputs(set((snmNode, ))))

            selectedNodes = []

            for node in nodes:
                if node in upstreamSet:
                    selectedNodes.append(node)
                else:
                    #any of my parents in there?
                    p = node.getParent()
                    while p:
                        if p in upstreamSet:
                            selectedNodes.append(node)
                            break

                        p = p.getParent()

            nodes = selectedNodes
        else:

            if str(self.__scopePopup.currentText()).startswith('Selected'):
                selectedNodes = []
                allSelected = set(NodegraphAPI.GetAllSelectedNodes())
                for node in nodes:
                    p = node
                    while p:
                        if p in allSelected:
                            selectedNodes.append(node)
                            break
                        p = p.getParent()

                nodes = selectedNodes

        return nodes
示例#11
0
def setParameterNodeGraph(parameter_name,
                          value,
                          time=1.0,
                          t='',
                          selected=False,
                          recursive=False):
    '''
    this method set the given paramter to the given value on all the nodes in the node graph,
    if selected is True, then only selected nodes will be affected,
    if recursive is True, then the group nodes will be expanded recursivly if any,
    
    By default, we set the value at time 1.0, this can be changed by specifying the time, and
    node with any type will be targeted. If you want to shrink the nodes down to the type of 'Alembic_In' 
    for instance, then you can specify t='Alembic_In'

    obsoleted:
    if strictly is True, then we use strict name matching rule to look up the given parameters,
    otherwise it will be true if the lower case of the given parameter name is included in the lower 
    case of the parameter name on the nodes.
    '''
    if t and isinstance(t, str):
        nodes = NodegraphAPI.GetAllNodesByType(t)
    else:
        nodes = NodegraphAPI.GetAllNodes()
    if selected:
        sel_nodes = NodegraphAPI.GetAllSelectedNodes()
        if recursive:
            sel_nodes = ng_traverseGroupDown(sel_nodes)
        nodes = list(set(nodes).intersection(sel_nodes))
    # set attribute
    log = ''
    for n in nodes:
        # lets try to access the parameter directly
        param = n.getParameter(parameter_name)
        if param:
            param.setUseNodeDefault(False)
            param.setValue(value, time)
            log += ('%s: %s at time %s\n') % (param.getFullName(), str(value),
                                              str(time))
            continue
        # get the parameters' objects
        params = setParameters({parameter_name: [value, time]}, n)
        if params:
            log += ('%s: %s at time %s\n') % (params[0].getFullName(),
                                              str(value), str(time))
    if log:
        print log
示例#12
0
def getParameters(parameter_name='',
                  node=[],
                  param_type='any',
                  matchMode='tail'):
    '''
    set the given parameter and value on the selected(or given) node
    input parameter name should be a list or string
    the returned type is a dict if given the parameter_name: 
        {parameter_name:[parameter_object, ...]}
    or a list if the parameter_name is invalid, in this case, we simply list all parameters:
        [parameter_name, ...]
    '''
    if not node:
        sel = NodegraphAPI.GetAllSelectedNodes()
    else:
        sel = node
        if not isinstance(sel, list):
            sel = [sel]
    if not isinstance(parameter_name, list):
        parameter_name = [parameter_name]
    if parameter_name and parameter_name[0]:
        collections = {}
    else:
        collections = []

    for s in sel:
        #get the parameters
        params = traverseParameterGroup(s.getParameters())
        for p in params:
            if param_type != 'any' and p.getType() != param_type:
                continue
            if parameter_name and parameter_name[0]:
                for n in parameter_name:
                    if ( matchMode=='tail' and p.getFullName().lower().endswith(n.lower()) ) or \
                        ( matchMode=='include' and n.lower() in p.getFullName().lower() ):
                        if collections.has_key(n):
                            collections[n].append(p)
                        else:
                            collections.update({n: [p]})
                        print p.getFullName()
            else:
                collections.append(p)
                print p.getFullName()
    return collections
示例#13
0
    def createStandard(self):
        pos = NodegraphAPI.GetViewPortPosition(NodegraphAPI.GetRootNode())
        renderer = RenderingAPI.RenderPlugins.GetDefaultRendererPluginName()
        if renderer == 'arnold':
            fileName = os.path.join(self.resources, 'arnold_standard.katana')
        elif renderer == 'prman':
            fileName = os.path.join(self.resources, 'prman_standard.katana')
        else:
            QtGui.QMessageBox.warning(
                None, 'Error', '{} plugin not found!'.format(renderer.upper()))
            return

        if os.path.exists(fileName):
            KatanaFile.Import(fileName, floatNodes=False)
            imported = NodegraphAPI.GetAllSelectedNodes()[-1]
            NodegraphAPI.SetNodePosition(imported, ((pos[0][0]), pos[0][1]))
        else:
            QtGui.QMessageBox.warning(None, 'Error',
                                      'There is no standard material saved!')
示例#14
0
def addAllCamToRenderManager(layerName = 'ALL', camPattern = 'CameraLeftShape'):
    nodeSelected = NodegraphAPI.GetAllSelectedNodes()
    renderManagerNode = None
    for node in nodeSelected:
        if node.getType() != 'RenderManager':
            nodeSelected.remove(node)
    if len(nodeSelected) > 1:
        raise NameError('Select only 1 RenderManager node')
    elif len(nodeSelected) == 0:
        nodeRender = NodegraphAPI.GetAllNodesByType('RenderManager', includeDeleted=False)
        if len(nodeRender) == 0:
            raise NameError("there is no RenderManager in the scene, create one")
        elif len(nodeRender) > 1:
            raise NameError('Select  1 RenderManager node')
        else:
            renderManagerNode = nodeRender[0]
    else:
        renderManagerNode = nodeSelected[0]

    rndLayer = None
    for item in renderManagerNode.getRenderLayers():
        if item.getName() == layerName:
            rndLayer = item
        else:
            rndLayer = renderManagerNode.addRenderLayer(layerName)

    producer = Nodes3DAPI.GetGeometryProducer(renderManagerNode, 0)
    camproducer = producer.getProducerByPath("/root/world/cam")
    children = []
    allCameraPath =[]
    kAttr.walkChildrenProducer(camproducer, children)
    cameraPath = None
    for child in children :
         if child.getType() == "camera" and child.getFullName().find(camPattern ) > 0:
              allCameraPath.append(child.getFullName())
    for cam in sorted(allCameraPath):
        rendrOutput = renderManagerNode.addRenderOutput(cam,rndLayer)
        renderNode = rendrOutput.getRenderNode()
        start = renderNode.getParameter('user.start')
        end = renderNode.getParameter('user.end')
        start.setExpressionFlag(False)
        end.setExpressionFlag(False)
示例#15
0
def get_selected_nodes(single=False):
    """
    Get selected nodes from the node graph, if single is given will
    check if a single node is selected.

    Kwargs:
        single (bool): single node selection
    
    Returns:
        list. Selected nodes.
    
    #FIXME (eze) this should return arrays, even is single is on
    """
    nodes = NodegraphAPI.GetAllSelectedNodes()
    if single:
        if len(nodes) != 1:
            raise RuntimeError("Please select 1 node.")
        return nodes[0]
    else:
        return nodes
示例#16
0
 def set_parent(self):
     selected_nodes = NodegraphAPI.GetAllSelectedNodes()
     if not selected_nodes:
         return
     output_ports = selected_nodes[-1].getOutputPorts()
     outport = None
     inputport = None
     for output_port in output_ports:
         connected_port = output_port.getConnectedPorts()
         outport = output_port
         if not connected_port:
             continue
         inputport = connected_port[-1]
         break
     if outport:
         outport.connect(self.getInputPort('input'))
     dx, dy = 0, 0
     if inputport:
         self.getOutputPort('output').connect(inputport)
         dx, dy = NodegraphAPI.GetNodePosition(inputport.getNode())
     ux, uy = NodegraphAPI.GetNodePosition(selected_nodes[-1])
     mx = (ux + dx) / 2
     my = (uy + dy) / 2
     NodegraphAPI.SetNodePosition(self, [mx, my])
示例#17
0
    def importMtl(self):
        pos = NodegraphAPI.GetViewPortPosition(NodegraphAPI.GetRootNode())
        currentItemName = str(self.listWidget.currentItem().text())
        checkCat = str(self.catedoryCB.currentText())

        if not checkCat == 'ALL':
            fileName = os.path.join(self.directory, checkCat,
                                    currentItemName + '.katana')
        else:
            fileName = os.path.join(
                str(self.listWidget.currentItem().data(
                    QtCore.Qt.UserRole).toPyObject()),
                currentItemName + '.katana')

        if os.path.exists(fileName):
            KatanaFile.Import(fileName, floatNodes=False)
            imported = NodegraphAPI.GetAllSelectedNodes()[-1]
            DrawingModule.SetCustomNodeColor(imported, 0.2, 0.4, 0.1)
            NodegraphAPI.SetNodePosition(imported, ((pos[0][0]), pos[0][1]))
        else:
            QtGui.QMessageBox.information(
                None, currentItemName,
                'There is no Material for {}, try importing Look File!'.format(
                    currentItemName))
示例#18
0
def createSingleBlocker(
        root=NodegraphAPI.GetRootNode(), celExp='getParent().', topNode=True):
    #open the file contening the lua file
    #fileLua = open(__LUA_FILE_PATH,'r')
    #luaText = fileLua.read()
    # root node
    rootNode = root
    #create the groupNode
    groupNode = NodegraphAPI.CreateNode('Group', rootNode)
    groupNode.setName('Blocker1')
    name = groupNode.getName()
    #add in and out port
    groupNodeIn = groupNode.addInputPort('in')
    groupNodeOut = groupNode.addOutputPort('out')
    #add attribute to switch the display of group node to normal node
    groupNodeAttrDict = {'ns_basicDisplay': 1, 'ns_iconName': ''}
    groupNode.setAttributes(groupNodeAttrDict)
    #add the disable param
    disableParam = groupNode.getParameters().createChildNumber('disable', 0)
    newCelExp = celExp[:celExp.rfind(
        'getParent().')]  # this is a hack it work but not safe
    disableParam.setExpression(newCelExp + name + '.disable', True)
    #create user param on the groupNode if use as a single entity
    if topNode:
        paramui(groupNode, name)

    #create the opNode who create the primitive
    primitiveOpNode = NodegraphAPI.CreateNode('OpScript', parent=groupNode)
    primitiveOpNode.setName('primitiveType')
    primitiveOpNode.getParameter('applyWhere').setValue(
        'at specific location', 0)
    primitiveOpNode.getParameter('location').setExpression(
        celExp + name + '.path_Name', True)
    #create parameter
    primitiveOpNodeParam = primitiveOpNode.getParameters().createChildGroup(
        'user')
    #param for message
    primitiveOpNodeParamDisplay = primitiveOpNodeParam.createChildNumber(
        'message', 1)
    primitiveOpNodeParamDisplay.setExpression(celExp + name + '.message', True)
    #param to get the color
    primitiveOpNodeParamColor = primitiveOpNodeParam.createChildNumberArray(
        'color', 3)
    primitiveOpNodeParamColor.setExpression(celExp + name + '.color', True)
    #param to get the light
    primitiveOpNodeParamLight = primitiveOpNodeParam.createChildString(
        'light', '')
    primitiveOpNodeParamLight.setExpression(celExp + name + '.CEL', True)
    #param to get the shape
    primitiveOpNodeParamShape = primitiveOpNodeParam.createChildString(
        'shape', 'box')
    primitiveOpNodeParamShape.setExpression(celExp + name + '.blocker_Type',
                                            True)
    #this part is to use if you want the "printed script" in the lua script tab
    #filePrimitiveStart = luaText.find('--PrimitiveModule')
    #filePrimitiveEnd = luaText.find('--endPrimitiveModule')
    #primitiveOpNode.getParameter('script.lua').setValue(luaText[filePrimitiveStart:filePrimitiveEnd],0)
    #this is using a lua script as reference which mean you need to set the LUA_PATH correctly to point at the script(i.eos.environ['LUA_PATH'] = "/homes/duda/.katana/LuaScript/?.lua")
    primitiveOpNode.getParameter('script.lua').setValue(
        "local createPrimitive = require 'blocker'\ncreatePrimitive.primitive()",
        0)

    #create the transform Node
    transformNode = NodegraphAPI.CreateNode('Transform3D', parent=groupNode)
    transformNode.setName('Transform_Blocker')
    #set the path expression
    transformNode.getParameter('path').setExpression(
        celExp + name + '.path_Name', True)
    #set the interactive to Yes
    transformNode.getParameter('makeInteractive').setValue('Yes', 0)

    #create the opScriptNode for the primitive and set it's lua text to get the transform matrix
    opscriptPrimNode = NodegraphAPI.CreateNode('OpScript', parent=groupNode)
    opscriptPrimNode.setName('MatrixPrim')
    opscriptPrimNode.getParameter('CEL').setExpression(
        celExp + name + '.path_Name', True)
    #this part is to use if you want the "printed script" in the lua script tab
    #fileMatrixTextStart = luaText.find('--MatrixModule')
    #fileMatrixTextEnd = luaText.find('--endMatrixModule')
    #opscriptPrimNode.getParameter('script.lua').setValue(luaText[fileMatrixTextStart:fileMatrixTextEnd],0)
    #this is using a lua script as reference which mean you need to set the LUA_PATH correctly to point at the script(i.eos.environ['LUA_PATH'] = "/homes/duda/.katana/LuaScript/?.lua")
    opscriptPrimNode.getParameter('script.lua').setValue(
        "local createMatrix = require 'blocker'\ncreateMatrix.getMatrix()", 0)

    #create the opscript for the light
    opscriptLightNode = NodegraphAPI.CreateNode('OpScript', groupNode)
    opscriptLightNode.getParameter('CEL').setExpression(
        celExp + name + ".CEL", True)
    opscriptLightNode.setName('MatrixLight')
    opscriptLightUserParam = opscriptLightNode.getParameters(
    ).createChildGroup('user')
    opscriptLightUserParamBlocker = opscriptLightUserParam.createChildString(
        'blocker', 'blk01')
    opscriptLightUserParamBlocker.setExpression(
        celExp + name + '.blocker_Number', True)
    opscriptLightUserParamPrim = opscriptLightUserParam.createChildString(
        'primitive', '')
    opscriptLightUserParamPrim.setExpression(celExp + name + '.path_Name',
                                             True)
    listParam = ['density', 'roundness', 'width_edge', 'height_edge', 'ramp']
    for param in listParam:
        paramCreated = opscriptLightUserParam.createChildNumber(param, 0.0)
        paramCreated.setExpression(celExp + name + '.' + param, True)
    opscriptLightUserParamShape = opscriptLightUserParam.createChildString(
        'geometry_type', 'box')
    opscriptLightUserParamShape.setExpression(celExp + name + '.blocker_Type',
                                              True)
    opscriptLightUserParamAxis = opscriptLightUserParam.createChildString(
        'axis', 'x')
    opscriptLightUserParamAxis.setExpression(celExp + name + '.axis', True)
    opscriptLightUserParamFileIn = opscriptLightUserParam.createChildString(
        'fileIn', '')
    opscriptLightUserParamFileIn.setExpression(celExp + name + '.fileIn', True)
    opscriptLightUserParamUseProj = opscriptLightUserParam.createChildNumber(
        'use_projection', 0)
    opscriptLightUserParamUseProj.setExpression(
        celExp + name + '.use_projection', True)
    opscriptLightUserParamFileType = opscriptLightUserParam.createChildNumber(
        'file_type', 0)
    opscriptLightUserParamFileType.setExpression(celExp + name + '.file_type',
                                                 True)
    #noise user param
    dictParamNoise = {
        'noise_octaves': 'number',
        'noise_distortion': 'number',
        'noise_lacunarity': 'number',
        'noise_amplitude': 'number',
        'noise_scale': 'array',
        'noise_offset': 'array',
        'noise_coord_space': 'string'
    }
    for param in dictParamNoise.keys():
        paramToCreate = None
        if dictParamNoise[param] == 'number':
            paramToCreate = opscriptLightUserParam.createChildNumber(
                param, 0.0)
        elif dictParamNoise[param] == 'array':
            paramToCreate = opscriptLightUserParam.createChildNumberArray(
                param, 3)
        else:
            paramToCreate = opscriptLightUserParam.createChildString(param, '')
        paramToCreate.setExpression(celExp + name + '.noise.' + param, True)

    #this part is to use if you want the "printed script" in the lua script tab
    #fileLightStart = luaText.find('--MatrixLight')
    #fileLightEnd = luaText.find('--endMatrixLight')
    #opscriptLightNode.getParameter('script.lua').setValue(luaText[fileLightStart:fileLightEnd],0)
    #this is using a lua script as reference which mean you need to set the LUA_PATH correctly to point at the script(i.eos.environ['LUA_PATH'] = "/homes/duda/.katana/LuaScript/?.lua")
    opscriptLightNode.getParameter('script.lua').setValue(
        "local paramLight = require 'blocker'\nparamLight.applyBlockerParam()",
        0)

    #create the mergeNode
    mergeNode = NodegraphAPI.CreateNode('Merge', groupNode)
    mergeNode.setName('MergePrim')
    mergeNode.addInputPort('i0')
    mergeNode.addInputPort('i1')

    #connection
    sendGroup = groupNode.getSendPort('in')
    returnGroup = groupNode.getReturnPort('out')
    mergeNode.getInputPort('i0').connect(sendGroup)
    primitiveOpNode.getOutputPort('out').connect(
        transformNode.getInputPort('in'))
    transformNode.getOutputPort('out').connect(mergeNode.getInputPort('i1'))
    mergeNode.getOutputPort('out').connect(opscriptPrimNode.getInputPort('i0'))
    opscriptPrimNode.getOutputPort('out').connect(
        opscriptLightNode.getInputPort('i0'))
    opscriptLightNode.getOutputPort('out').connect(returnGroup)

    #placement of Nodes
    centralPos = NodegraphAPI.GetNodePosition(mergeNode)
    NodegraphAPI.SetNodePosition(primitiveOpNode,
                                 (centralPos[0] + 100, centralPos[1] + 200))
    NodegraphAPI.SetNodePosition(transformNode,
                                 (centralPos[0] + 100, centralPos[1] + 100))
    NodegraphAPI.SetNodePosition(opscriptPrimNode,
                                 (centralPos[0], centralPos[1] - 100))
    NodegraphAPI.SetNodePosition(opscriptLightNode,
                                 (centralPos[0], centralPos[1] - 200))

    #close the lua file
    #fileLua.close()

    #put the node under the mouse if single node
    if topNode:
        currentSelection = NodegraphAPI.GetAllSelectedNodes()
        for node in currentSelection:
            NodegraphAPI.SetNodeSelected(node, False)
        NodegraphAPI.SetNodeSelected(groupNode, True)
        # Get list of selected nodes
        nodeList = NodegraphAPI.GetAllSelectedNodes()
        # Find Nodegraph tab and float nodes
        nodegraphTab = UI4.App.Tabs.FindTopTab('Node Graph')
        if nodegraphTab:
            nodegraphTab.floatNodes(nodeList)

    return groupNode
示例#19
0
def getSelectedNodes():
    return NodegraphAPI.GetAllSelectedNodes()
示例#20
0
def createKatanaNodes(fileOut = '/tmp/fileDispFromLua.txt'):
    # check if there is a node ('Attribute_Disp') existing if yes delete it
    # existingNode = NodegraphAPI.GetNode('Attribute_Disp')
    # if existingNode :
    #     inputNodePort = existingNode.getInputPortByIndex(0)
    #     outputNodePort = existingNode.getOutputPortByIndex(0)
    #     inputNodePort.connect(outputNodePort)
    #     existingNode.delete()
    inputFile = open(fileOut,'a')
    node = NodegraphAPI.GetAllSelectedNodes()[0] # select the node
    nodePos = NodegraphAPI.GetNodePosition(node) # get the position of node
    nodeOutPort = node.getOutputPortByIndex(0) # get the output port
    nextPort = nodeOutPort.getConnectedPorts()[0] # get the first connected port from the previous node

    # create the opscript node
    root = NodegraphAPI.GetRootNode()
    opscriptFindDisp = NodegraphAPI.CreateNode('OpScript',root)
    opscriptFindDisp.setName('findDisp')
    opscriptFindDisp.getParameter('CEL').setValue('/root/world//*{hasattr("materialOverride.parameters.dsp_map")}',0)
    opscriptFindDispUserParam = opscriptFindDisp.getParameters().createChildGroup('user')
    opscriptFindDispUserParamFileOut = opscriptFindDispUserParam.createChildString('fileOut',fileOut)
    opscriptFindDisp.getParameter('script.lua').setValue("local getdispMap = require 'dispFunc'\ngetdispMap.getDispMap()",0)
    opscriptFindDispInPort = opscriptFindDisp.getInputPort('i0')
    opscriptFindDispOutPort = opscriptFindDisp.getOutputPort('out')
    nodeOutPort.connect(opscriptFindDispInPort)
    opscriptFindDispOutPort.connect(nextPort)
    NodegraphAPI.SetNodePosition(opscriptFindDisp, (nodePos[0]+50,nodePos[1]-50))
    opscriptFindDispPos = NodegraphAPI.GetNodePosition(opscriptFindDisp)
    # set the view and the edit on the opscript node
    NodegraphAPI.SetNodeViewed(opscriptFindDisp, True, exclusive=True)
    NodegraphAPI.SetNodeEdited(opscriptFindDisp, True, exclusive=True)

    # dummy functions to run the opscript and create the file
    sg = ScenegraphManager.getActiveScenegraph()
    node = NodegraphAPI.GetNode( 'root' )
    time = NodegraphAPI.GetCurrentTime()
    producer = Nodes3DAPI.GetGeometryProducer( node, time)
    prod = producer.getProducerByPath('/root')
    WalkBoundAttrLocations(prod)

    # extract the dip for each map
    assetWithDisp = findDispHeight(fileOut)

    # create a stack of AttributeSet to set the disp if there is element in the dict
    if len(assetWithDisp.keys()):
        stack = NodegraphAPI.CreateNode("GroupStack", NodegraphAPI.GetRootNode())
        stack.setName('Attribute_Disp')
        stack.setChildNodeType("AttributeSet")
        listWord = ['/location/','/prop/','/location/','/character/']
        for key in assetWithDisp.keys():
            path = ''
            attributSet = stack.buildChildNode()
            attributSet.getParameter('mode').setValue('CEL',0)
            attrPath = attributSet.getParameter('celSelection')
            attributSet.getParameter('attributeType').setValue('float',0)
            # replace the word from listWord by the wildcard '/*' so to work in lighting scene
            for word in listWord:
                if key.find(word) > 1:
                    path = key.replace(word,'//*/')
                    attrPath.setValue(path,0)
                    break
                else:
                    attrPath.setValue(key,0)
            attributSet.setName(key[key.rfind('/')+1:]) # set name to the _hi
            attrValue = attributSet.getParameter('numberValue.i0')
            attrValue.setValue(assetWithDisp[key],0)
            attrName = attributSet.getParameter('attributeName')
            attrName.setValue('arnoldStatements.disp_padding',0)
        NodegraphAPI.SetNodePosition(stack,opscriptFindDispPos)
        stackInPort = stack.getInputPort('in')
        stackOutPort = stack.getOutputPort('out')
        nodeOutPort.connect(stackInPort)
        stackOutPort.connect(nextPort)
        NodegraphAPI.SetNodeViewed(stack, True, exclusive=True)
        NodegraphAPI.SetNodeEdited(stack, True, exclusive=True)
    else:  # reconnect the nodes
        nodeOutPort.connect(nextPort)
        NodegraphAPI.SetNodeViewed(node, True, exclusive=True)
        NodegraphAPI.SetNodeEdited(node, True, exclusive=True)

    # delete the opscript and the file
    opscriptFindDisp.delete()
    os.remove(fileOut)
    print 'finished'
示例#21
0
def get_current_node():
    knodes = NodegraphAPI.GetAllSelectedNodes()
    if not knodes:
        return None
    return knodes[-1].getName()
def createCam(seq='s0060', camDict={}):
    # print getNewOrder(camDict)
    pos = (0, 0)
    mergeInput = 0
    maxOutTime = 0
    inputName = 'i'
    camFrame = _STARTTIME_
    # set the sart time of the project to _STARTTIME_ and end time to 500
    root = NodegraphAPI.GetRootNode()
    root.getParameter('inTime').setValue(_STARTTIME_, 0)
    root.getParameter('outTime').setValue(500, 0)

    # find the number of camera
    nbCamNode = len(camDict.keys())

    # create a group node which will contains all the camera for the sequence
    group = NodegraphAPI.CreateNode("Group", NodegraphAPI.GetRootNode())
    group.setName('PublishedCam_Group_' + seq)
    # add attribute to switch the display of group node to normal node
    groupNodeAttrDict = {'ns_basicDisplay': 1, 'ns_iconName': ''}
    group.setAttributes(groupNodeAttrDict)
    group.addOutputPort('out')
    # create parameter for the group node
    celParamOutCam = group.getParameters().createChildNumber('outputCam', 0)
    celParamOutCam.setHintString(
        "{'options__order': ['All', 'masterCam'], 'help': 'choose if all the camera of the sequences will be display in the SceneGraph or only the masterCam', 'widget': 'mapper', 'options': {'All': 0.0, 'masterCam': 1.0}}"
    )
    outTypeParam = group.getParameters().createChildNumber('outputType', 0)
    outTypeParam.setHintString(
        "{'options__order': ['stereo', 'left', 'center', 'right'], 'help': 'out cam type (i.e: stereo,Left,Center or Right)', 'widget': 'mapper', 'options': {'stereo': 0.0, 'right': 3.0, 'center': 2.0, 'left': 1.0}}"
    )
    # create the merge node which assemble al the camera
    mergeNode = NodegraphAPI.CreateNode('Merge', group)
    NodegraphAPI.SetNodeComment(
        mergeNode, "merge all the sequence cameras and the masterCam together")
    # create the switch Node
    switchNode = NodegraphAPI.CreateNode('Switch', group)
    NodegraphAPI.SetNodeComment(
        switchNode,
        "switch between all cameras to create the masterCam animation")
    switchNodeIn = switchNode.getParameter('in')

    for key in getOrder(camDict):
        # start the animation process of the switch node if we are at the startframe value
        if camFrame == _STARTTIME_:
            switchNodeIn.setAutoKey(True)
            switchNodeIn.setValueAutoKey(0, _STARTTIME_)
        # create the PublishedCamera Node
        PublishedCameraNode = NodegraphAPI.CreateNode('PublishedCamera', group)
        # set the Name of the PublishedCamera node
        PublishedCameraNode.setName('Cam_' + key)
        # set the path of the camera abc
        camFile = PublishedCameraNode.getParameter('file')
        camFile.setValue(camDict[key]['camPath'], 0)

        # set the name for the camera in the camera tree
        camName = PublishedCameraNode.getParameter('name')
        camName.setValue('/root/world/cam/Cam_' + key, 0)
        # set the position of the node
        NodegraphAPI.SetNodePosition(PublishedCameraNode, pos)
        # create a new input connection on the merge and connect the PublishedCamera node to it
        inputName = 'i' + str(mergeInput)
        mergeNode.addInputPort(inputName)
        PublishedCameraNode.getOutputPort('out').connect(
            mergeNode.getInputPort(inputName))

        # create the timeOfset node
        timeOffsetNode = NodegraphAPI.CreateNode('TimeOffset', group)
        timeOffsetNode.setName('TimeOffset_Cam' + key)
        # set value for the inputFrame parameter of the timeOffset node
        inputFrame = timeOffsetNode.getParameter('inputFrame')
        inputFrame.setExpressionFlag(False)
        inputFrame.setAutoKey(True)
        allFramesInterest = camDict[key]['frameInterest']
        # if there is multiple frameInterest loop
        for frame in allFramesInterest:
            inputFrame.setValueAutoKey(frame, camFrame)
            camFrame += 1
        inputFrame.setAutoKey(False)
        # position the timeOffset node
        NodegraphAPI.SetNodePosition(timeOffsetNode, (pos[0], pos[1] - 50))
        PublishedCameraNode.getOutputPort('out').connect(
            timeOffsetNode.getInputPort('input'))

        # create the RenameNode
        renameNode = NodegraphAPI.CreateNode('Rename', group)
        # set the name of the rename
        renameNode.setName('Rename_Cam_' + key)
        # set the rootlocation for the rename node
        renameNode.getParameter('rootLocation').setValue('/root/world/cam', 0)
        # set the pattern
        renameNode.getParameter('pattern').setValue('Cam_' + key, 0)
        # set the replace string
        renameNode.getParameter('replace').setValue('MasterCam', 0)
        # position of the rename node
        NodegraphAPI.SetNodePosition(renameNode, (pos[0], pos[1] - 100))
        # connect the publishedcam node to the rename Node
        timeOffsetNode.getOutputPort('output').connect(
            renameNode.getInputPort('in'))
        # connect the rename node to the switch node
        switchNode.addInputPort(inputName)
        renameNode.getOutputPort('out').connect(
            switchNode.getInputPort(inputName))

        # increment the input nb for the merge node
        mergeInput += 1
        # set the next key for the switch node(with inputMerge incremented) if inputMerge is less than the number of cam node
        if mergeInput < nbCamNode:
            switchNodeIn.setValueAutoKey(mergeInput, camFrame)
        else:
            switchNodeIn.setAutoKey(False)

        # increment the pos
        pos = (pos[0] + 300, pos[1])
        # find the maxOutTime
        if allFramesInterest[-1] > maxOutTime:
            maxOutTime = allFramesInterest[-1]

    # set the animation curve of the switch to be constant
    curve = switchNodeIn.getCurve()
    segments = curve.getSegments()
    for seg in segments:
        seg.setExpression('constant()')

    # position of the merge node
    mergePos = (pos[0] / 2, -300)
    NodegraphAPI.SetNodePosition(mergeNode, mergePos)

    # create the switch node to output all camera or only the master camera
    switchMasterNode = NodegraphAPI.CreateNode('Switch', group)
    switchMasterNode.setName('switchMasterNode')
    NodegraphAPI.SetNodeComment(switchMasterNode,
                                'swich to all camera or only masterCam')
    switchMasterNode.getParameter('in').setExpression('getParent().outputCam',
                                                      True)
    # connect the port
    switchMasterNode.addInputPort('i0')
    switchMasterNode.addInputPort('i1')
    mergeNode.getOutputPort('out').connect(switchMasterNode.getInputPort('i0'))
    switchNode.getOutputPort('output').connect(
        switchMasterNode.getInputPort('i1'))
    # position the switchMasterNode
    switchMasterNodePos = (mergePos[0], mergePos[1] - 50)
    NodegraphAPI.SetNodePosition(switchMasterNode, switchMasterNodePos)

    # position for the switch node
    NodegraphAPI.SetNodePosition(switchNode, (mergePos[0] + 300, -200))
    # connect the switch node to the merge node
    inputName = 'i' + str(mergeInput)
    mergeNode.addInputPort(inputName)
    switchNode.getOutputPort('output').connect(
        mergeNode.getInputPort(inputName))

    # create the opscript node to add the masterCam in the cameraList
    opscriptNode = NodegraphAPI.CreateNode('OpScript', group)
    opscriptNode.setName('addCamMasterToCamList')
    opscriptNodeParam = opscriptNode.getParameters().createChildGroup('user')
    opscriptNodeParam.createChildNumber('outCamValue', 0)
    opscriptNode.getParameter('user.outCamValue').setExpression(
        'getParent().outputCam', True)
    opscriptNodeParam.createChildNumber('outCamType', 0)
    opscriptNode.getParameter('user.outCamType').setExpression(
        'getParent().outputType', True)
    NodegraphAPI.SetNodeComment(
        opscriptNode,
        "add the masterCam center,left and right to the cameraList ")
    opscriptNode.getParameter('CEL').setValue('/root/world', 0)
    # set the script node
    # opscriptNode.getParameter('script.lua').setValue("local camVal = Interface.GetOpArg('user.outCamValue'):getValue()"
    #                                                  "\nlocal camType = Interface.GetOpArg('user.outCamType'):getValue()"
    #                                                  "\nlocal tableCamList = {}"
    #                                                  "\nif camVal == 1 then"
    #                                                  "\n\tif camType == 0 then"
    #                                                  "\n\t\ttable.insert(tableCamList,'/root/world/cam/MasterCam/stereoCamera/stereoCameraCenterCamShape')"
    #                                                  "\n\t\ttable.insert(tableCamList,'/root/world/cam/MasterCam/stereoCameraLeft/stereoCameraLeftShape')"
    #                                                  "\n\t\ttable.insert(tableCamList,'/root/world/cam/MasterCam/stereoCameraRight/stereoCameraRightShape')"
    #                                                  "\n\telseif(camType == 1) then"
    #                                                  "\n\t\ttable.insert(tableCamList,'/root/world/cam/MasterCam/stereoCameraLeft/stereoCameraLeftShape')"
    #                                                  "\n\telseif camType == 2 then"
    #                                                  "\n\t\ttable.insert(tableCamList,'/root/world/cam/MasterCam/stereoCamera/stereoCameraCenterCamShape')"
    #                                                  "\n\telse"
    #                                                  "\n\t\ttable.insert(tableCamList,'/root/world/cam/MasterCam/stereoCameraRight/stereoCameraRightShape')"
    #                                                  "\n\tend"
    #                                                  "\nelse"
    #                                                  "\n\tlocal camList = Interface.GetAttr('globals.cameraList')"
    #                                                  "\n\ttableCamList = camList:getNearestSample(0)"
    #                                                  "\n\ttable.insert(tableCamList,'/root/world/cam/MasterCam/stereoCamera/stereoCameraCenterCamShape')"
    #                                                  "\n\ttable.insert(tableCamList,'/root/world/cam/MasterCam/stereoCameraLeft/stereoCameraLeftShape')"
    #                                                  "\n\ttable.insert(tableCamList,'/root/world/cam/MasterCam/stereoCameraRight/stereoCameraRightShape')"
    #                                                  "\nend"
    #                                                  "\nInterface.SetAttr('globals.cameraList',StringAttribute(tableCamList))",0)
    opscriptNode.getParameter('script.lua').setValue(opNodeScript, 0)
    # connect the opscriptnode to the merge node
    switchMasterNode.getOutputPort('output').connect(
        opscriptNode.getInputPort('i0'))
    opscriptNodePos = (mergePos[0], mergePos[1] - 100)
    NodegraphAPI.SetNodePosition(opscriptNode, opscriptNodePos)

    # create  prunes nodes to switch off non disired cameras
    # prune for left cam
    pruneNodeLeft = NodegraphAPI.CreateNode('Prune', group)
    pruneNodeLeft.setName('leftCam_' + seq)
    # set the cel node to eliminate all camera but the left one
    pruneNodeLeft.getParameter('cel').setValue(
        "((/root/world/cam/Cam_s*/stereoCameraRight /root/world/cam/Cam_s*/stereoCamera /root/world/cam/MasterCam/stereoCameraRight /root/world/cam/MasterCam/stereoCamera))",
        0)
    # connect the merge group to the prune node
    opscriptNode.getOutputPort('out').connect(pruneNodeLeft.getInputPort('A'))
    prunePos = (mergePos[0] - 200, mergePos[1] - 200)
    NodegraphAPI.SetNodePosition(pruneNodeLeft, prunePos)
    # prune for right cam
    pruneNodeRight = NodegraphAPI.CreateNode('Prune', group)
    pruneNodeRight.setName('rightCam_' + seq)
    # set the cel node to eliminate all camera but the right ones
    pruneNodeRight.getParameter('cel').setValue(
        "((/root/world/cam/Cam_s*/stereoCameraLeft /root/world/cam/Cam_s*/stereoCamera /root/world/cam/MasterCam/stereoCameraLeft /root/world/cam/MasterCam/stereoCamera))",
        0)
    # connect the merge group to the prune node
    opscriptNode.getOutputPort('out').connect(pruneNodeRight.getInputPort('A'))
    prunePos = (mergePos[0] + 200, mergePos[1] - 200)
    NodegraphAPI.SetNodePosition(pruneNodeRight, prunePos)
    # prune for center cam
    pruneNodeCenter = NodegraphAPI.CreateNode('Prune', group)
    pruneNodeCenter.setName('centerCam_' + seq)
    # set the cel node to eliminate all camera but the center ones
    pruneNodeCenter.getParameter('cel').setValue(
        "((/root/world/cam/Cam_s*/stereoCameraRight /root/world/cam/Cam_s*/stereoCameraLeft /root/world/cam/MasterCam/stereoCameraLeft /root/world/cam/MasterCam/stereoCameraRight))",
        0)
    # connect the merge group to the prune node
    opscriptNode.getOutputPort('out').connect(
        pruneNodeCenter.getInputPort('A'))
    prunePos = (mergePos[0], mergePos[1] - 200)
    NodegraphAPI.SetNodePosition(pruneNodeCenter, prunePos)

    # create the switch node for the prune camera
    switchPrune = NodegraphAPI.CreateNode('Switch', group)
    switchPrune.setName('switchPrune')
    NodegraphAPI.SetNodeComment(switchPrune,
                                'swich to to prune the non needed camera')
    switchPrune.getParameter('in').setExpression('getParent().outputType',
                                                 True)
    # connect the port
    switchPrune.addInputPort('i0')
    switchPrune.addInputPort('i1')
    switchPrune.addInputPort('i2')
    switchPrune.addInputPort('i3')
    opscriptNode.getOutputPort('out').connect(switchPrune.getInputPort('i0'))
    pruneNodeLeft.getOutputPort('out').connect(switchPrune.getInputPort('i1'))
    pruneNodeCenter.getOutputPort('out').connect(
        switchPrune.getInputPort('i2'))
    pruneNodeRight.getOutputPort('out').connect(switchPrune.getInputPort('i3'))
    # position the switchPrune
    switchPrunePos = (mergePos[0], mergePos[1] - 300)
    NodegraphAPI.SetNodePosition(switchPrune, switchPrunePos)

    # connect the switchprune to the out port of the group
    returnGroup = group.getReturnPort('out')
    switchPrune.getOutputPort('output').connect(returnGroup)
    # set the out time of the project to maxOutTime
    root.getParameter('outTime').setValue(camFrame - 1, 0)
    print maxOutTime, camFrame

    # put the node under the mouse
    currentSelection = NodegraphAPI.GetAllSelectedNodes()
    for node in currentSelection:
        NodegraphAPI.SetNodeSelected(node, False)
    NodegraphAPI.SetNodeSelected(group, True)
    # Get list of selected nodes
    nodeList = NodegraphAPI.GetAllSelectedNodes()
    # Find Nodegraph tab and float nodes
    nodegraphTab = UI4.App.Tabs.FindTopTab('Node Graph')
    if nodegraphTab:
        nodegraphTab.floatNodes(nodeList)
示例#23
0
#This script will create a Transform3D for each location selected in the
#scenegraph below the selected node.
import sys
from Katana import Nodes3DAPI
from Katana import NodegraphAPI
from Katana import ScenegraphManager
#Get scenegraph seletion.
selectedGroups = ScenegraphManager.getActiveScenegraph().getSelectedLocations()
#Get seleted node
try:
    baseNode = NodegraphAPI.GetNode(
        NodegraphAPI.GetAllSelectedNodes()[0].getName())
except:
    sys.exit("Select a node on the nodegraph")

for i in selectedGroups:
    y = 50  #inital node position on nodegraph
    try:
        previousNode = NodegraphAPI.GetNode(
            NodegraphAPI.GetAllSelectedNodes()[0].getName())
    except IndexError:
        break
    previousNodePosition = NodegraphAPI.GetNodePosition(previousNode)
    xpos = previousNodePosition[0]
    ypos = previousNodePosition[1] - y
    t3d = NodegraphAPI.CreateNode("Transform3D", NodegraphAPI.GetRootNode())
    t3d.getParameter("path").setValue(i, 0)
    t3d.getParameter("makeInteractive").setValue("Yes", 0)
    NodegraphAPI.SetNodePosition(t3d, [xpos, ypos])
    #ports change names so trying more than one.
    try: