def AddAlembicGeometry(importomaticNode, assetId, locationExpression=None): assetPlugin = AssetAPI.GetDefaultAssetPlugin() rootInstanceName = assetPlugin.getAssetDisplayName(assetId) node = NodegraphAPI.CreateNode('Group') node.setName(rootInstanceName) # This seems a bit odd to set the name and then retrieve it but Katana # will change the name to a unique name which we can then extract uniqueRootName = node.getName() node.setName(uniqueRootName) node.setType('Alembic') node.addOutputPort('out') alembicInNode = NodegraphAPI.CreateNode('Alembic_In', node) alembicInNode.getOutputPortByIndex(0).connect(node.getReturnPort('out')) # If the location parameter isn't # given try to intelligently guess one # if locationExpression: alembicInNode.getParameter('name').setExpression(locationExpression, True) else: baseLocation = "/root/world/geo" location = baseLocation + "/" + uniqueRootName alembicInNode.getParameter('name').setValue(location, 0) alembicInNode.getParameter('abcAsset').setValue(assetId, 0) assetInfoParam = node.getParameters().createChildGroup('assetInfo') findInstances(uniqueRootName, assetInfoParam, "") BuildScenegraph(node) return node
def createRestParts(self, InData): root = (InData[2][0] - 100, InData[2][1] - 100) mergeNode = NodegraphAPI.CreateNode('Merge', NodegraphAPI.GetRootNode()) NodegraphAPI.SetNodePosition(mergeNode, root) mergeNode.addInputPort('i%d' % 0) mergeNode.addInputPort('i%d' % 1) mergeNode.getInputPort("i0").connect(InData[0].getOutputPort("out")) mergeNode.getInputPort("i1").connect(InData[1].getOutputPort("out")) upstreamDot = NodegraphAPI.CreateNode('Dot', NodegraphAPI.GetRootNode()) downstreamDot = NodegraphAPI.CreateNode('Dot', NodegraphAPI.GetRootNode()) NodegraphAPI.SetNodePosition(downstreamDot, (root[0] - 400, root[1])) NodegraphAPI.SetNodePosition(upstreamDot, (root[0] - 400, root[1] + 200)) downstreamDot.getInputPort("input").connect( upstreamDot.getOutputPort("output")) origNode = InData[3] upstreamDot.getInputPort("input").connect( origNode.getOutputPort("out")) LookFileBakeNode = NodegraphAPI.CreateNode('LookFileBake', NodegraphAPI.GetRootNode()) NodegraphAPI.SetNodePosition(LookFileBakeNode, (root[0] - 200, root[1] - 100)) LookFileBakeNode.getInputPort("orig").connect( downstreamDot.getOutputPort("output")) LookFileBakeNode.getInputPort("default").connect( mergeNode.getOutputPort("out"))
def setUpClass(cls): '''Procedurally create nodes for testing.''' # Add a PxrUsdIn node and set its motion sample times pxrUsdInNode = NodegraphAPI.CreateNode('PxrUsdIn', NodegraphAPI.GetRootNode()) pxrUsdInNode.getParameter('motionSampleTimes').setValue('0 -1', 0) # Add a RenderSettings node and turn on motion blur renderSettingsNode = NodegraphAPI.CreateNode( 'RenderSettings', NodegraphAPI.GetRootNode()) mts = renderSettingsNode.getParameter( 'args.renderSettings.maxTimeSamples') mts.getChild('value').setValue(2, 0) mts.getChild('enable').setValue(1, 0) sc = renderSettingsNode.getParameter( 'args.renderSettings.shutterClose') sc.getChild('value').setValue(0.5, 0) sc.getChild('enable').setValue(1, 0) # Connect the two nodes together and view from the RS node pxrUsdInNode.getOutputPortByIndex(0).connect( renderSettingsNode.getInputPortByIndex(0)) NodegraphAPI.SetNodeViewed(renderSettingsNode, True, True) # Set the current frame NodegraphAPI.SetCurrentTime(50)
def InitializeNode(smNode): smNode.hideNodegraphGroupControls() smNode.addInputPort('inputScene') smNode.addInputPort('sharedDeps') smNode.addOutputPort('originalScene') # Merge node exists so that we have a valid scene even with # nothing plugged in mergeNode = NodegraphAPI.CreateNode('Merge', smNode) mergeNode.addInputPort('i0').connect(smNode.getSendPort('inputScene')) mergeDot = NodegraphAPI.CreateNode('Dot', smNode) mergeDot.getInputPortByIndex(0).connect(mergeNode.getOutputPortByIndex(0)) attr = mergeDot.getAttributes() attr['ns_basicDisplay'] = True mergeDot.setAttributes(attr) sceneDot1 = NodegraphAPI.CreateNode('Dot', smNode) sceneDot1.getInputPortByIndex(0).connect(mergeDot.getOutputPortByIndex(0)) sceneDot1.getOutputPortByIndex(0).connect( smNode.getReturnPort('originalScene')) sharedDepDotNode = NodegraphAPI.CreateNode('Dot', smNode) sharedDepDotNode.getInputPortByIndex(0).connect( smNode.getSendPort('sharedDeps')) NodegraphAPI.SetNodePosition(mergeNode, (-200, 100)) NodegraphAPI.SetNodePosition(mergeDot, (-200, 0)) NodegraphAPI.SetNodePosition(sharedDepDotNode, (100, 100)) NodegraphAPI.SetNodePosition(sceneDot1, (-350, RENDER_NODE_POSITION)) AddNodeReferenceParam(smNode, 'mergeNode', mergeNode) AddNodeReferenceParam(smNode, 'mergeDot', mergeDot) AddNodeReferenceParam(smNode, 'sharedDepDotNode', sharedDepDotNode)
def build(self): informationTuple = self.depthDigger() materialNodeMap = informationTuple[0] levelNodeMap = informationTuple[1] nodeDataMap = informationTuple[2] nodeMergeList = [] """Reset node position""" i = 0 for materialNodes in materialNodeMap: i += 1 offsetX = (i-1)*500 #~ Create a group to hold some nodes in single material groupNode = NodegraphAPI.CreateNode('Group', NodegraphAPI.GetRootNode()) groupName = "%s_%s"%(materialNodes,self.suffixGroup) groupNode.setName(groupName) NodegraphAPI.SetNodePosition(groupNode, (0 + offsetX, 0)) #~ Create a Network Material Node networkMaterialNode = NodegraphAPI.CreateNode('NetworkMaterial', NodegraphAPI.GetRootNode()) NodegraphAPI.SetNodePosition(networkMaterialNode, (0 + offsetX, -250)) materialName = "%s_%s"%(materialNodes,self.suffixNetworkMaterial) networkMaterialNode.getParameter('name').setValue(str(materialName), 0) networkMaterialNode.addInputPort('arnoldSurface') networkMaterialNode.addInputPort('arnoldBump') nodeMergeList.append(networkMaterialNode) tempLevelCount = {} for node in materialNodeMap[materialNodes]: for level in levelNodeMap: if node in levelNodeMap[level]: if tempLevelCount.has_key(level): tempLevelCount[level] += 1 else: tempLevelCount[level] = 1 for node in materialNodeMap[materialNodes]: thisLevel = 1 for level in levelNodeMap: if node in levelNodeMap[level]: thisLevel = level offsetY = (thisLevel - 1)*100 name = str(node) offset = (offsetX,offsetY) type = str(nodeDataMap[name][0]) paraList = nodeDataMap[name][1] """Create""" activeNode = self.createNodes(name,offset,type,paraList) activeNode.setParent(groupNode) upstreamMergeNode = self.createMergeNodes(nodeMergeList, NodegraphAPI.GetRootNode()) NodegraphAPI.SetNodePosition(upstreamMergeNode,((len(nodeMergeList)/2)*500, -600)) upstreamMergeNode.setName("MaterialsMerge") dowmstreamMergeNode = NodegraphAPI.CreateNode('Merge',NodegraphAPI.GetRootNode()) dowmstreamMergeNode.addInputPort('i%d' % 0) dowmstreamMergeNode.getInputPort("i0").connect(upstreamMergeNode.getOutputPort("out")) NodegraphAPI.SetNodePosition(dowmstreamMergeNode,((len(nodeMergeList)/2)*500, -1000)) dowmstreamMergeNode.setName("MergePass") self.pos = ((len(nodeMergeList)/2)*500, -1000) """Connect""" self.connectNodes() Result = dowmstreamMergeNode return Result
def createAlembicNode(self): AlembicData = self.AlembicData MaterialData = self.MaterialData # Create Node modelName = "Model_In" nodeList = [] standardNode = NodegraphAPI.CreateNode('Alembic_In', NodegraphAPI.GetRootNode()) #standardNode.getParameter('name').setValue("/root/world/geo/%s"%modelName, 0) #standardNode.setName(modelName) standardNode.getParameter('abcAsset').setValue( "C:/Users/mili/Desktop/c_NGJL_mod.abc", 0) NodegraphAPI.SetNodePosition(standardNode, (0, 0)) nodeList.append(standardNode) pruneNode = NodegraphAPI.CreateNode('Prune', NodegraphAPI.GetRootNode()) NodegraphAPI.SetNodePosition(standardNode, (0, 50)) pruneNode.getInputPort('A').connect(standardNode.getOutputPort('out')) nodeList.append(pruneNode) facesetGroupNode = NodegraphAPI.CreateNode('GroupStack', NodegraphAPI.GetRootNode()) facesetGroupNode.setName("FaceSetGroup") facesetGroupNode.setChildNodeType('FaceSetCreate') facesetGroupNode.getInputPort('in').connect( pruneNode.getOutputPort('out')) NodegraphAPI.SetNodePosition(facesetGroupNode, (0, -50)) nodeList.append(facesetGroupNode) materialassignGroupNode = NodegraphAPI.CreateNode( 'GroupStack', NodegraphAPI.GetRootNode()) materialassignGroupNode.setName("MaterialAssignGroup") materialassignGroupNode.setChildNodeType('MaterialAssign') materialassignGroupNode.getInputPort('in').connect( facesetGroupNode.getOutputPort('out')) NodegraphAPI.SetNodePosition(materialassignGroupNode, (0, -100)) nodeList.append(materialassignGroupNode) nodegraphTab = UI4.App.Tabs.FindTopTab('Node Graph') for data in AlembicData: self.createFaceSet(facesetGroupNode, data) for material in MaterialData: data = (material, MaterialData[material]) self.createMatrialAssign(materialassignGroupNode, data) pruneNode = NodegraphAPI.GetNode("Prune") pruneList = [ '/root/world/geo/%s/front' % modelName, '/root/world/geo/%s/persp' % modelName, '/root/world/geo/%s/side' % modelName, '/root/world/geo/%s/top' % modelName, ] pruneNode.getParameter('cel').setValue('(' + ' '.join(pruneList) + ')', 0) if nodegraphTab: nodegraphTab.floatNodes(nodeList)
def make_node_networks(knode, asset_inputs): input_dot = NodegraphAPI.CreateNode('Dot', parent=knode) output_dot = NodegraphAPI.CreateNode('Dot', parent=knode) ing, x, y = 300, 0, 0 dot_x = ing * (len(asset_inputs)) / 2 NodegraphAPI.SetNodePosition(input_dot, [dot_x, 0]) NodegraphAPI.SetNodePosition(output_dot, [dot_x, -300]) pipe_parameter = knode.getParameter('studio_pipe') for category in studio_nodes.CATEGORIES: if category not in asset_inputs: continue for asset in asset_inputs[category]: output_define = create_output_define(knode) output_define.setName('%s_output_define' % asset) render_node = NodegraphAPI.CreateNode('Render', parent=knode) render_node.setName('%s_render' % asset) render_node.getParameter('passName').setValue( '%s_render' % asset, 1.0) render_parameter = render_node.getParameters() render_asset_name = render_parameter.createChildString( 'asset_name', asset) hint = {'readOnly': 'True'} render_asset_name.setHintString(str(hint)) NodegraphAPI.SetNodePosition(output_define, [x, -100]) NodegraphAPI.SetNodePosition(render_node, [x, -200]) x += ing # dependency connections input_dot.getOutputPort('output').connect( output_define.getInputPort('input')) input_dot.getOutputPort('output').connect( output_dot.getInputPort('input')) output_define.getOutputPort('out').connect( render_node.getInputPort('input')) knode.getSendPort('input').connect(input_dot.getInputPort('input')) output_dot.getOutputPort('output').connect( knode.getReturnPort('output')) # set expressions attributes = { 'color_space': 'args.renderSettings.outputs.outputName.rendererSettings.colorSpace.value', 'file_extension': 'args.renderSettings.outputs.outputName.rendererSettings.fileExtension.value', 'render_camera': 'args.renderSettings.outputs.outputName.rendererSettings.cameraName.value', 'render_location': 'args.renderSettings.outputs.outputName.locationSettings.renderLocation.value' } for driver, driven in attributes.items(): if driver == 'render_location': name = '/%s/%s.' % (asset, asset) extension = 'self.getNode().getParent().getParameter(\'studio_pipe.file_extension\').getValue(1.0)' expression = 'self.getNode().getParent().getParameter(\'%s.%s\').getValue(1.0) + \'%s\' + %s' % ( 'studio_pipe', driver, name, extension) else: expression = 'self.getNode().getParent().getParameter(\'%s.%s\').getValue(1.0)' % ( 'studio_pipe', driver) driven_parameter = output_define.getParameter(driven) driven_parameter.setExpression(expression)
def create(cls, enclosingNode, locationPath): """ Creates the contents of the EditStackNode that contains the edit nodes. This could be any other kind of node with at least one input and one output, but the createPackageEditStackNode() helper function does all of the configuration boilerplate code of an EditStackNode for you. The return value is a ArnoldSpotLightGafferEditPackage instance. This particular package node will contain a TransformEdit node on it, which will allow to edit the transform of a spot light. """ # Create the package node. Since this is an edit package we want to use # an EditStackNode instead of a GroupNode, since it already has an # input and an output by default. This also adds some necessary # parameters to this node. packageNode = cls.createPackageEditStackNode(enclosingNode, locationPath) # Build material edit node materialNode = NodegraphAPI.CreateNode('Material', packageNode) actionParam = materialNode.getParameter('action') actionParam.setValue('edit material', 0) editLocationParam = materialNode.getParameter('edit.location') editLocationParam.setExpression('=^/__gaffer.location') editLocationParam.setExpressionFlag(True) NU.AddNodeRef(packageNode, 'material_edit', materialNode) packageNode.buildChildNode(adoptNode=materialNode) # Build transform edit node transformEditNode = NodegraphAPI.CreateNode('TransformEdit', packageNode) actionParam = transformEditNode.getParameter('action') actionParam.setValue('override interactive transform', 0) pathParam = transformEditNode.getParameter('path') pathParam.setExpression('=^/__gaffer.location') pathParam.setExpressionFlag(True) # Adds reference parameters to the transform edit node NU.AddNodeRef(packageNode, 'transform_edit', transformEditNode) # Add the transform edit node into the package node using # EditStackNode's buildChildNode(). packageNode.buildChildNode(adoptNode=transformEditNode) # Create and append light linking nodes linkingNodes = Packages.LinkingMixin.getLinkingNodes(packageNode, create=True) NU.AppendNodes( packageNode, tuple(linkingNode for linkingNode in linkingNodes if linkingNode is not None)) # Instantiate a package with the package node return cls.createPackage(packageNode)
def addOutput(self, desiredName): port = self.addOutputPort(desiredName) returnPort = self.getReturnPort(port.getName()) subGroup = NodegraphAPI.CreateNode('Group', self) subGroup.addOutputPort('out') subGroup.getOutputPortByIndex(0).connect(returnPort) merge = NodegraphAPI.CreateNode('Merge', subGroup) merge.getOutputPortByIndex(0).connect(subGroup.getReturnPort('out')) return port.getName()
def create_puppet_group(knode, contents, position, ing): ''' :description create asset groups and its dependency nodes :param knode <NodegraphAPI node object> :param contents <dict> :param position <list> :param ing <int> ''' puppet_group = NodegraphAPI.CreateNode('Group', parent=knode) puppet_group.setName('%s_group' % contents['name']) NodegraphAPI.SetNodePosition(puppet_group, position) puppet_group.addOutputPort('out') merge_node = create_merge_node([0, 0], puppet_group, contents['name']) input_port = merge_node.addInputPort('input') look_resolve, look_assign = None, None if contents['category'] != 'camera': look_resolve = NodegraphAPI.CreateNode('LookFileResolve', parent=puppet_group) look_resolve.setName('%s_resolve' % contents['name']) look_resolve.getOutputPort('out').connect(input_port) look_assign = NodegraphAPI.CreateNode('LookFileAssign', parent=puppet_group) look_assign.setName('%s_klf' % contents['name']) look_assign.getOutputPort('out').connect( look_resolve.getInputPort('A')) input_port = look_assign.getInputPort('input') klf_parameter = look_assign.getParameter('args.lookfile.asset') expression = get_expression('lookdev', contents['category'], contents['name'], 'i3') klf_parameter.getChild('value').setExpression(expression) klf_parameter.getChild('enable').setValue(True, 1.0) cel_parameter = look_assign.getParameter('CEL') puppet_location = os.path.join(studio_nodes.SCENE_GRAPH_LOCATION, contents['category'], contents['name']) cel_parameter.setValue(puppet_location.encode(), 1.0) alembic_node = NodegraphAPI.CreateNode('Alembic_In', parent=puppet_group) alembic_node.setName('%s_alembic' % contents['name']) alembic_node.getOutputPort('out').connect(input_port) scenegraph_location = os.path.join(studio_nodes.SCENE_GRAPH_LOCATION, contents['category']) name_parameter = alembic_node.getParameter('name') name_parameter.setValue(scenegraph_location.encode(), 1.0) name_parameter.setUseNodeDefault(False) abc_parameter = alembic_node.getParameter('abcAsset') expression = get_expression('animation', contents['category'], contents['name'], 'i5') abc_parameter.setExpression(expression) abc_parameter.setUseNodeDefault(False) # set the position x, y = [0, 100] for each in [look_resolve, look_assign, alembic_node]: if not each: continue NodegraphAPI.SetNodePosition(each, [x, y]) y += ing return puppet_group
def createShadingNetwork(cls, parentNode=None, xPos=0, yPos=0): """ Convenience function to create the shading network for our SkyDome. Can be called from inside Katana using: C{Plugins.GafferThreeAPI.PackageClasses.SkyDomePackage.createShadingNetwork()} """ if parentNode is None: parentNode = NodegraphAPI.GetRootNode() # Create shading network imageNode = NodegraphAPI.CreateNode('ArnoldShadingNode', parentNode) imageNode.getParameter('name').setValue('skyDomeImage', 0) NodegraphAPI.SetNodePosition(imageNode, (xPos, yPos + 120)) imageNode.getParameter('nodeType').setValue('image', 0) imageNode.checkDynamicParameters() lightNode = NodegraphAPI.CreateNode('ArnoldShadingNode', parentNode) lightNode.getParameter('name').setValue('skyDomeLight', 0) NodegraphAPI.SetNodePosition(lightNode, (xPos, yPos + 80)) lightNode.getParameter('nodeType').setValue('skydome_light', 0) lightNode.checkDynamicParameters() lightNode.getInputPort('color').connect(imageNode.getOutputPort('out')) hdriLightNode = NodegraphAPI.CreateNode('NetworkMaterial', parentNode) hdriLightNode.getParameter('name').setValue('hdriSkyDomeLight', 0) NodegraphAPI.SetNodePosition(hdriLightNode, (xPos, yPos + 40)) hdriLightNode.addInputPort('arnoldSurface') hdriLightNode.getInputPort('arnoldSurface').connect( lightNode.getOutputPort('out')) lookFileMaterialsOutNode = NodegraphAPI.CreateNode( 'LookFileMaterialsOut', parentNode) lookFileMaterialsOutNode.setName('hdriSkiDomeLight_bake') NodegraphAPI.SetNodePosition(lookFileMaterialsOutNode, (xPos, yPos)) lookFileMaterialsOutNode.getParameter('saveTo').setValue( cls.DEFAULT_BAKED_LIGHT_FILENAME, 0) lookFileMaterialsOutNode.getInputPort('in').connect( hdriLightNode.getOutputPort('out')) # Expose shading node parameters on the network material cls.__exposeShaderParameter(imageNode, 'filename', 'HDRI_map', {'widget': 'fileInput'}) cls.__exposeShaderParameter(imageNode, 'sflip') cls.__exposeShaderParameter(imageNode, 'tflip') cls.__exposeShaderParameter(imageNode, 'multiply', 'color') cls.__exposeShaderParameter(lightNode, 'matrix') cls.__exposeShaderParameter(lightNode, 'intensity') cls.__exposeShaderParameter(lightNode, 'exposure') cls.__exposeShaderParameter(lightNode, 'samples') return lookFileMaterialsOutNode
def create_viewer_settings(attribute_name): """ Create viewer color settings. Creates a group stack with 1 group node per unique attribute_name value. This can used to find values of surfacing attributes as in attribute_name = "geometry.arbitrary.surfacing_object" attribute_name = "geometry.arbitrary.surfacing_project' Args: attribute_name (str): name of the attribute Returns: None """ rootNode = NodegraphAPI.GetRootNode() material_stack = NodegraphAPI.CreateNode("GroupStack", rootNode) material_stack.setName("Surfacing_viewer_settings") selected_node = katana.get_selected_nodes(single=True) attribute_values = katana.get_objects_attribute_values( selected_node, attribute_name) position_y = 0 for attribute_value in attribute_values: random_color = utils.get_random_color(attribute_value) viewer_settings = NodegraphAPI.CreateNode("ViewerObjectSettings", rootNode) viewer_settings.setName("viewerColor_%s" % attribute_value) katana.add_node_to_group_last(material_stack, viewer_settings, inputPort="input") viewer_settings_value = viewer_settings.getParameter( "args.viewer.default.drawOptions.color") viewer_settings_value.getChild("value").getChild("i0").setValue( random_color[0], 0) viewer_settings_value.getChild("value").getChild("i1").setValue( random_color[1], 0) viewer_settings_value.getChild("value").getChild("i2").setValue( random_color[2], 0) viewer_settings_value.getChild("enable").setValue(True, 0) cel_statement = '/root/world//*{attr("%s.value") == "%s"}' % ( attribute_name, attribute_value, ) viewer_settings.getParameter("CEL").setValue(cel_statement, 0) NodegraphAPI.SetNodePosition(viewer_settings, (0, position_y)) position_y = position_y - 50
def __init__(self): self.hideNodegraphGroupControls() self.addOutputPort('default') self.getParameters().parseXML('\n' '<group_parameter>\n' '<string_parameter name="__nodePanel" value="Importatomic"/>\n' '<number_parameter name="__pluginRevision" value="1"/>\n' '</group_parameter>') subGroup = NodegraphAPI.CreateNode('Group', self) subGroup.addOutputPort('out') subGroup.getOutputPortByIndex(0).connect(self.getReturnPort('default')) merge = NodegraphAPI.CreateNode('Merge', subGroup) merge.getOutputPortByIndex(0).connect(subGroup.getReturnPort('out'))
def importLmtl(self): pos = NodegraphAPI.GetViewPortPosition(NodegraphAPI.GetRootNode()) currentItemName = str(self.listWidget.currentItem().text()) checkCat = str(self.catedoryCB.currentText()) if not checkCat == 'ALL': klfName = os.path.join(self.directory, checkCat, currentItemName + '.klf') expression = 'path.join(getenv("MATLIB",0), "material_library", "{}", "{}")'.format( checkCat, currentItemName + '.klf') else: klfName = os.path.join( str(self.listWidget.currentItem().data( QtCore.Qt.UserRole).toPyObject()), currentItemName + '.klf') expression= 'path.join(getenv("MATLIB",0), "material_library", "{}", "{}")'\ .format(str(self.listWidget.currentItem().data(QtCore.Qt.UserRole).toPyObject()).split(os.sep)[-1], currentItemName+'.klf') if os.path.exists(klfName): materialNode = NodegraphAPI.CreateNode('Material', NodegraphAPI.GetRootNode()) materialNode.getParameter('name').setValue(currentItemName, 0) DrawingModule.SetCustomNodeColor(materialNode, 0.2, 0.27, 0.4) materialNode.getParameter('action').setValue( 'create from Look File', 0) materialNode.getParameter('lookfile.lookfile').setExpression( expression) NodegraphAPI.SetNodePosition(materialNode, ((pos[0][0]), pos[0][1])) materialAssign = NodegraphAPI.CreateNode( 'MaterialAssign', NodegraphAPI.GetRootNode()) materialAssign.setName('MA_' + currentItemName) materialAssign.getParameter( 'args.materialAssign.value').setExpression( "scenegraphLocationFromNode(getNode('{}'))".format( materialNode.getName())) DrawingModule.SetCustomNodeColor(materialAssign, 0.2, 0.27, 0.4) NodegraphAPI.SetNodePosition(materialAssign, ((pos[0][0]), pos[0][1] - 50)) materialNode.getOutputPort('out').connect( materialAssign.getInputPort('input')) NodegraphAPI.SetNodeEdited(materialAssign, edited=True, exclusive=True) else: QtGui.QMessageBox.information( None, currentItemName, 'There in no Look File for {}, try importing Material!'.format( currentItemName))
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)
def ActionCallback(value): """ Callback for the layered menu, which creates a PrmanShadingNode node and sets its B{nodeType} parameter to the given C{value}, which is the name of a PRMan shader as set for the menu entry in L{IkaPopulateCallback()}. @type value: C{str} @rtype: C{object} @param value: An arbitrary object that the menu entry that was chosen represents. In our case here, this is the name of a PRMan shader as passed to the L{LayeredMenuAPI.LayeredMenu.addEntry()} function in L{IkaPopulateCallback()}. @return: An arbitrary object. In our case here, we return the created PrmanShadingNode node, which is then placed in the B{Node Graph} tab because it is a L{NodegraphAPI.Node} instance. """ # Remove ris/ or osl/ prefix from the node name. if (value.find('ris/') == 0 or value.find('osl/') == 0): name = value[4:] else: name = value # Create a node containing the chosen type. if (name.find('integrator') == 0): node = NodegraphAPI.CreateNode('PrmanIntegratorSettings', NodegraphAPI.GetRootNode()) else: node = NodegraphAPI.CreateNode('PrmanShadingNode', NodegraphAPI.GetRootNode()) node.getParameter('nodeType').setValue(value, 0) # Set the node's name. node.setName(name) node.getParameter('name').setValue(node.getName(), 0) # Set the node's color based on its shader category. for category in colorDict: if (category in name): color = colorDict[category] DrawingModule.SetCustomNodeColor(node, color[0], color[1], color[2]) break # Update the Node Graph. for tab in UI4.App.Tabs.GetTabsByType('Node Graph'): tab.update() return node
def create_collections(attribute_name): """ Create collections by attribute values. Creates a group stack with 1 collection create node per unique attribute_name value. This can used to find values of surfacing attributes as in attribute_name = "geometry.arbitrary.surfacing_object" attribute_name = "geometry.arbitrary.surfacing_project' Args: attribute_name (str): name of the attribute Returns: list: collections names """ rootNode = NodegraphAPI.GetRootNode() selected_node = katana.get_selected_nodes(single=True) node_outPort = selected_node.getOutputPort("out") surfacing_projects = katana.get_objects_attribute_values( selected_node, attribute_name) group_stack = NodegraphAPI.CreateNode("GroupStack", rootNode) group_stack.setName("surfacing_collections") group_stack_inputPort = group_stack.getInputPort("in") node_outPort.connect(group_stack_inputPort) collections_name_list = [] position_y = 0 for surfacing_project in surfacing_projects: collection_create = NodegraphAPI.CreateNode("CollectionCreate", rootNode) collection_name = "%s" % surfacing_project collection_create.setName(collection_name) collections_name_list.append(surfacing_project) # collection_create_location = collection_create.getParameter('/') # collection_create_location.setValue(location,0) collection_create_name = collection_create.getParameter("name") collection_create_name.setValue("%s" % surfacing_project, 0) collection_create_cel = collection_create.getParameter("CEL") collection_create_cel.setValue( '/root/world//*{attr("%s.value") == "%s"}' % (attribute_name, surfacing_project), 0, ) katana.add_node_to_group_last(group_stack, collection_create) NodegraphAPI.SetNodePosition(collection_create, (0, position_y)) position_y = position_y - 50 return collections_name_list
def build(self,InPos): offsetX = InPos[0] - 200 offsetY = InPos[1] AlembicData = self.AlembicData MaterialData = self.MaterialData #~ Create Node modelName = "asset" nodeList = [] self.standardNode = NodegraphAPI.CreateNode('Alembic_In', NodegraphAPI.GetRootNode()) self.standardNode.getParameter('name').setValue("/root/world/geo/%s"%modelName, 0) self.standardNode.setName("Asset") self.standardNode.getParameter('abcAsset').setValue("C:/Users/mili/Desktop/c_NGJL_mod.abc", 0) NodegraphAPI.SetNodePosition(self.standardNode, (0+offsetX, 150+offsetY)) nodeList.append(self.standardNode) pruneNode = NodegraphAPI.CreateNode('Prune', NodegraphAPI.GetRootNode()) NodegraphAPI.SetNodePosition(pruneNode, (0+offsetX, 100+offsetY)) pruneNode.getInputPort('A').connect(self.standardNode.getOutputPort('out')) nodeList.append(pruneNode) pruneList = [ '/root/world/geo/%s/front'%modelName, '/root/world/geo/%s/persp'%modelName, '/root/world/geo/%s/side'%modelName, '/root/world/geo/%s/top'%modelName, ] pruneNode.getParameter('cel').setValue('(' + ' '.join(pruneList) + ')', 0) facesetGroupNode = NodegraphAPI.CreateNode('GroupStack', NodegraphAPI.GetRootNode()) facesetGroupNode.setName("FaceSetGroup") facesetGroupNode.setChildNodeType('FaceSetCreate') facesetGroupNode.getInputPort('in').connect(pruneNode.getOutputPort('out')) NodegraphAPI.SetNodePosition(facesetGroupNode, (0+offsetX, 50+offsetY)) nodeList.append(facesetGroupNode) materialassignGroupNode = NodegraphAPI.CreateNode('GroupStack', NodegraphAPI.GetRootNode()) materialassignGroupNode.setName("MaterialAssignGroup") materialassignGroupNode.setChildNodeType('MaterialAssign') materialassignGroupNode.getInputPort('in').connect(facesetGroupNode.getOutputPort('out')) NodegraphAPI.SetNodePosition(materialassignGroupNode, (0+offsetX, offsetY)) nodeList.append(materialassignGroupNode) for data in AlembicData: self.createFaceSet(facesetGroupNode,data) for material in MaterialData: data = (material,MaterialData[material]) self.createMatrialAssign(materialassignGroupNode,data) Result = materialassignGroupNode return Result
def getFilterAssetStackOutput(self, outputName, build=False): outputGroup = self.__getNodeConnectedToGroupPort(self, outputName) if not outputGroup: if build: raise TypeError("Output port '%s' doesn't exist" % outputName) return None port = outputGroup.getOutputPortByIndex(0) if not port: return None node = self.__getNodeConnectedToGroupPort(outputGroup, port.getName()) if not node: if build: raise TypeError('Internal Importatomic graph error') return None if node.getBaseType() == 'GroupStack': return node if not build: return None stack = NodegraphAPI.CreateNode('GroupStack', outputGroup) mergeOutputPort = node.getOutputPortByIndex(0) mergeConnectedPort = mergeOutputPort.getConnectedPort(0) mergeOutputPort.disconnect(mergeConnectedPort) stack.getInputPortByIndex(0).connect(mergeOutputPort) stack.getOutputPortByIndex(0).connect(mergeConnectedPort) NodegraphAPI.SetNodePosition(stack, (0, -100)) return stack
def create(gnode, path): hc = SA.GetHierarchyCreateNode(gnode) mms = SA.GetMasterMaterials(gnode) m = NodegraphAPI.CreateNode('Material') m.getParameters().createChildString('paramName', '') m.getParameters().createChildString('pathName', '') m.setType(PackageName) hcParam = hc.getParameterForLocation(path) m.getParameter('paramName').setExpression( 'getParam(%r).param.getFullName()' % hcParam.getFullName()) m.getParameter('pathName').setExpression( "'/%s' % str(paramName).split('.', 1)[-1].replace('.', '/')") m.getParameter('action').setValue('edit material', 0) m.getParameter('edit.location').setExpression('pathName') m.getParameter('makeInteractive').setValue('Yes', 0) hcAttrs = hc.getAttrsParameterForLocation(path, create=True) gafferAttr = hcAttrs.createChildString('gaffer_type', 'master material') mms.buildChildNode(adoptNode=m) SA.ReorderMasterMaterials(gnode) SA.BuildLookFileMaterialParametersForPath(gnode, path) SA.AddNodeReferenceParam(m, 'node_material', m) SA.AddNodeReferenceForPath(gnode, path, 'package', m) return m
def ActionCallback(value): """ Callback for the layered menu, which creates a ShadingNode node and sets its B{nodeType} parameter to the given C{value}, which is the name of a shader as set for the menu entry in L{PopulateCallback()}. @type value: C{str} @rtype: C{object} @param value: An arbitrary object that the menu entry that was chosen represents. In our case here, this is the name of a dl shader as passed to the L{LayeredMenuAPI.LayeredMenu.addEntry()} function in L{PopulateCallback()}. @return: An arbitrary object. In our case here, we return the created ShadingNode node, which is then placed in the B{Node Graph} tab because it is a L{NodegraphAPI.Node} instance. """ renderer = RenderingAPI.RenderPlugins.GetDefaultRendererPluginName() if renderer == 'dl': shadingNodeType = 'DlShadingNode' elif renderer == 'arnold': shadingNodeType = 'ArnoldShadingNode' elif renderer == 'prman': shadingNodeType = 'PrmanShadingNode' elif renderer == 'vray': shadingNodeType = 'VrayShadingNode' elif renderer == 'Redshift': shadingNodeType = 'RedshiftShadingNode' # Create the node, set its shader, and set the name with the shader name node = NodegraphAPI.CreateNode(shadingNodeType) node.getParameter('nodeType').setValue(value, 0) node.setName(value) node.getParameter('name').setValue(node.getName(), 0) node.checkDynamicParameters() return node
def addLookFileNodes(groupNode, lookRef, lookCel, ignore='False', createNode='True'): # -- node graph -- noAssigns = 0 assignNodes = [] for childNode in groupNode.getChildren(): if childNode.getType() == "LookFileAssign": assignNodes.append(childNode) if createNode == 'True': # - LookFileAssign - nodeKstdAssign = NodegraphAPI.CreateNode('LookFileAssign') nodeKstdAssign.setParent(groupNode) nodeKstdAssign.getParameter('CEL').setExpressionFlag(True) nodeKstdAssign.getParameter('CEL').setExpression(lookCel) nodeKstdAssign.getParameter('args.lookfile.asset.enable').setValue( 1, 0) nodeKstdAssign.getParameter('args.lookfile.asset.value').setValue( lookRef, 0) assignNodes.append(nodeKstdAssign) if ignore == 'True': nodeKstdAssign.setBypassed(True) return nodeKstdAssign return None
def addPony(self, desiredName, index=-1): Utils.UndoStack.OpenGroup('Add pony to node "%s"' % self.getName()) try: ponyName = desiredName.replace('/', '_') ponyName = UniqueName.GetUniqueName( ponyName, self.getPonyNames().__contains__) mergeNode = SA.GetMergeNode(self) ponyNode = NodegraphAPI.CreateNode('PonyCreate', self) if index >= 0: ponyPort = mergeNode.addInputPortAtIndex('pony', index) else: ponyPort = mergeNode.addInputPort('pony') ponyNode.getOutputPortByIndex(0).connect(ponyPort) nameParam = ponyNode.getParameter('name') nameParam.setExpression('getParent().location + \'/\' + %r' % ponyName) nameParam.setExpressionFlag(True) self.cleanupInternalNetwork() return (ponyName, ponyPort.getIndex()) finally: Utils.UndoStack.CloseGroup()
def createShotGroup(self,root_node=None,shot=None): #======================================================================= # variable enable group --> live group --> live group --> gaffer three # variable enable group holds multiple gaffer threes... by default it will create none #======================================================================= sequence = self.getParameter('sequence').getValue(0) #sequence = self.sequence shot_string = '%s%s'%(settings.SHOT_PREFIX, shot) shot_VEG = NodegraphAPI.CreateNode('VariableEnabledGroup',root_node) shot_VEG.addOutputPort('out') shot_VEG.addInputPort('in') shot_VEG.getParameter('variableName').setValue('shot',0) shot_VEG.getParameter('pattern').setValue(shot,0) shot_VEG.setName(shot_string) shot_live_group = self.createGroup(shot_VEG,name=shot) sequence_param = root_node.getParameter('nodeReference').createChildString(shot_string,'') sequence_param.setExpressionFlag(True) sequence_param.setExpression('@%s'%shot_VEG.getName()) shot_live_group.getInputPortByIndex(0).connect(shot_VEG.getSendPort('in')) shot_live_group.getOutputPortByIndex(0).connect(shot_VEG.getReturnPort('out')) shot_live_group.getParameters().createChildString('version','') shot_live_group.getParameters().createChildString('hash','%s_%s'%(sequence,shot)) publish_dir = self.getParameter('publish_dir').getValue(0) + '/%s/shots/%s_%s'%(sequence,sequence,shot) if not os.path.exists(publish_dir): dir_list = ['gaffers','key','live_group','publish'] os.mkdir(publish_dir) for dir_item in dir_list: os.mkdir(publish_dir + '/%s'%dir_item) os.mkdir(publish_dir + '/%s/live'%dir_item) return shot_VEG
def createBlockGroup(self,root_node,name=None): if not name: name = 'block_01' group_node = NodegraphAPI.CreateNode('Group',root_node) group_node.setName(name) group_params = group_node.getParameters().createChildGroup('nodeReference') group_node.addOutputPort('out') group_node.addInputPort('in') key_group = self.createGroup(group_node,name='key') shot_group = self.createGroup(group_node,name='shots') vs_node = self.createVariableSwitch(group_node) add_params_node_list = [group_node, key_group, shot_group] #======================================================================= # PARAMETERS #======================================================================= self.createNodeReference(group_node,key_group,'key_node',param=group_params) self.createNodeReference(group_node,shot_group,'shot_group',param=group_params) self.createNodeReference(group_node,vs_node,'vs_node',param=group_params) self.createNodeReference(root_node,group_node,'block00',param=root_node.getParameter('nodeReference')) for node in add_params_node_list: version = node.getParameters().createChildString('version','') unique_hash = node.getParameters().createChildString('hash','') node.getParameters().createChildString('expanded','False') #======================================================================= # CONNECT #======================================================================= self.connectInsideGroup([key_group,shot_group,vs_node], group_node) group_node.getSendPort('in').connect(vs_node.getInputPortByIndex(0)) return group_node
def createOpScriptSample(groupNode = NodegraphAPI.GetRootNode(),name = 'sample',task='Object'): #expression root celExp = 'getParent().'+name #create the opscript for the samples opscriptSampleNode = NodegraphAPI.CreateNode('OpScript',groupNode) #set the expression for the CEL to be the one on parent node opscriptSampleNode.getParameter('CEL').setExpression(celExp+".CEL",True) #set the name of the opScript opscriptSampleNode.setName('Opscript_'+name) #param opscriptUserParam = opscriptSampleNode.getParameters().createChildGroup('user') if task == 'Object': opscriptSampleNode.getParameter('script.lua').setValue("local sample = require 'addSample'\nsample.Object()",0) listParam = ['diffuse_samples','sss_samples','backlighting_samples','glossy1_samples','glossy2_samples','transmission_samples'] for param in listParam: paramCreated = opscriptUserParam.createChildNumber(param,0.0) paramCreated.setExpression(celExp+'.'+param,True) elif task == 'Hair': opscriptSampleNode.getParameter('script.lua').setValue("local sample = require 'addSample'\nsample.Hair()",0) paramCreated = opscriptUserParam.createChildNumber('diffuse_samples',0.0) paramCreated.setExpression(celExp+'.'+'diffuse_samples',True) else: opscriptSampleNode.getParameter('script.lua').setValue("local sample = require 'addSample'\nsample.Light()",0) paramCreated = opscriptUserParam.createChildNumber('samples',0.0) paramCreated.setExpression(celExp+'.'+'samples',True) #param to enable/disable node disableParam = opscriptSampleNode.getParameters().createChildNumber('disable',0) disableParam.setExpression(celExp+'.disable',True) return opscriptSampleNode
def __init__(self): try: Utils.UndoStack.DisableCapture() try: self.setName("UsdMaterialBake") self.setType("UsdMaterialBake") networkVersion = "1.0" parameters_XML = _parameters_XML.format( networkVersion=networkVersion) self.getParameters().parseXML(parameters_XML) self.addInputPort("orig") self.addInputPort("default") self.addOutputPort("out") dot = NodegraphAPI.CreateNode('Dot', self) dot.getInputPortByIndex(0).connect(self.getSendPort("orig")) dot.getOutputPortByIndex(0).connect(self.getReturnPort("out")) NodegraphAPI.SetNodePosition(dot, (0, 200)) NodegraphAPI.SetNodeShapeAttr(self, 'basicDisplay', 1) NodegraphAPI.SetNodeShapeAttr(self, 'iconName', '') finally: Utils.UndoStack.EnableCapture() except Exception: log.exception("CREATE UsdMaterialBake FAILED.") raise self.__timer = None self.__interruptWidget = None
def importKlf(self): pos = NodegraphAPI.GetViewPortPosition(NodegraphAPI.GetRootNode()) currentItemName = str(self.listWidget.currentItem().text()) checkCat = str(self.catedoryCB.currentText()) if not checkCat == 'ALL': klfName = os.path.join(self.directory, checkCat, currentItemName + '.klf') expression = 'path.join(getenv("MATLIB",0), "material_library", "{}", "{}")'.format( checkCat, currentItemName + '.klf') else: klfName = os.path.join( str(self.listWidget.currentItem().data( QtCore.Qt.UserRole).toPyObject()), currentItemName + '.klf') expression= 'path.join(getenv("MATLIB",0), "material_library", "{}", "{}")'\ .format(str(self.listWidget.currentItem().data(QtCore.Qt.UserRole).toPyObject()).split(os.sep)[-1], currentItemName+'.klf') if os.path.exists(klfName): lfm = NodegraphAPI.CreateNode('LookFileMaterialsIn', NodegraphAPI.GetRootNode()) lfm.setName('LFMI_' + currentItemName) DrawingModule.SetCustomNodeColor(lfm, 0.4, 0, 0.15) lfm.getParameter('lookfile').setExpression(expression) NodegraphAPI.SetNodePosition(lfm, ((pos[0][0]), pos[0][1])) else: QtGui.QMessageBox.information( None, currentItemName, 'There is no Look File for {}, try importing Material!'.format( currentItemName))
def create_alembic_node(contents, position, current_asset, parent): ''' :description to create the alembic node inside the custom asset group :param contents <dict> :param position <list> :param current_asset <str> :param parent <NodegraphAPI node object> ''' alembic_node = NodegraphAPI.CreateNode('Alembic_In', parent=parent) alembic_node.setName('%s_abc' % contents['name']) NodegraphAPI.SetNodePosition(alembic_node, position) scenegraph_location = os.path.join( studio_nodes.SCENE_GRAPH_LOCATION, contents['category']) location_parameter = alembic_node.getParameter('name') location_parameter.setValue(scenegraph_location, 1.0) location_parameter.setUseNodeDefault(False) abc_parameter = alembic_node.getParameter('abcAsset') expression = get_expression(current_asset) abc_parameter.setExpression(expression) abc_parameter.setUseNodeDefault(False) source_path = abc_parameter.getValue(1.0) if not os.path.isfile(source_path): version = os.path.basename(os.path.split(source_path)[0]) message = 'not found %s version %s %s\n' % (contents['name'], version, source_path) QtGui.QMessageBox.warning(None, 'warning', message, QtGui.QMessageBox.Ok) return alembic_node
def create(gnode, path): flagGroup = SA.BuildLocationPackageForPath(gnode, path) flagGroup.setType(PackageName) flagGroup.setName(os.path.basename(path) + '_package') SA.AddNodeReferenceForPath(gnode, path, 'package', flagGroup) nodes = [] primCreate = NodegraphAPI.CreateNode('PrimitiveCreate', flagGroup) primCreate.addInputPort('in') primCreate.getParameter('name').setExpression('getParent().pathName') primCreate.getParameter('type').setValue('poly plane', 0) nodes.append(primCreate) material = NodegraphAPI.CreateNode('Material', flagGroup) material.getParameter('action').setValue('edit material', 0) material.getParameter('makeInteractive').setValue('Yes', 0) material.getParameter('edit.location').setExpression( 'str(getParent().pathName)+"/material"') material.getParameter('makeInteractive').setValue('Yes', 0) nodes.append(material) attrsParam = SA.GetAttributesParameterForPath(gnode, path, create=True) materialAssignParam = attrsParam.createChildString( 'materialAssign', '') materialAssignParam.setExpression( '"/"+getParamRelative(self, "../../../material").'\ 'param.getFullName(False).replace(".", "/")') arnoldObjectSettings = NodegraphAPI.CreateNode('ArnoldObjectSettings', flagGroup) arnoldObjectSettings.getParameter('CEL').setExpression( 'getParent().pathName') nodes.append(arnoldObjectSettings) SA.AddNodeReferenceParam(flagGroup, 'node_primCreate', primCreate) SA.AddNodeReferenceParam(flagGroup, 'node_material', material) SA.AddNodeReferenceParam(flagGroup, 'node_arnoldObjectSettings', arnoldObjectSettings) SA.WireInlineNodes(flagGroup, nodes)