Houdini, Python, Scripting

Houdini Snippet Vol.11 – Selection to Shelf Tool


Create a shelf tool – you can just drop a bunch of nodes to a shelf and voila… so the houdini docs. In some cases it works in some it doesn’t. I tried a small script.

Python Code (Prototype):

def create_shelf_tool_from_selection():
    try:
        ## Get specific ns_Tools shelf ##
        allShelves = hou.shelves.shelfSets()["shelf_set_1"] ## in my case this is located in set_1
        shelf_set1 = list(allShelves.shelves())
        ns_tool_shelf = None
        for shelf_item in shelf_set1:
            if shelf_item.name() == "ns_tools":             ## my custom shelf named ns_Tools ##
                ns_tool_shelf = shelf_item


        ## Get all selected nodes and create the python descriptions/code ##
        sel = hou.selectedNodes()

        if sel:
            parent = sel[0].parent()
            parentObj = hou.node(parent.path())

            ## Workaround with subnets to get the hole hierarchy ##
            subNet = parentObj.collapseIntoSubnet(sel, subnet_name="tmp")
            pyString = subNet.asCode(recurse=True, save_spare_parms=True)

            pyString += '''
## Extract the selected subnetwork ##   
sel = hou.selectedNodes()
sel[0].extractAndDelete()'''
            subNet.extractAndDelete()

            ## Create and handle new shelf tool ##
            tool_set = []
            current_tool_set = ns_tool_shelf.tools()
            for i in current_tool_set:
                tool_set.append(i)
            ## Tool name input window ##
            toolName = hou.ui.readInput("Enter a tool name:")[1]
            entry_folder = hou.hscriptExpression("$HSITE")
            pathShelfFile = (entry_folder + os.sep + "toolbar" + os.sep + "ns_Tools.shelf").replace("\\", "/")
            tool_set.append(hou.shelves.newTool(file_path=pathShelfFile, name=(toolName.replace(" ", "_")).lower(), label=toolName, script=pyString, language=hou.scriptLanguage.Python, icon="hicon:/SVGIcons.index?IM_NewViewport.svg"))
            ns_tool_shelf.setTools(tool_set)
        else:
            hou.ui.displayMessage("Select some Node(s)!")

    except Exception as e:
        hou.ui.displayMessage("Ooops, something went wrong.")
        print(e)