Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Switch viz for subnet folders:
- node = hou.pwd()
- parent = node.parent()
- return parent.evalParmTuple('folder0')[0]
- ****************************************************************************************************************************
- Mantra prep for farm:
- import hou, houdini_nodes
- def main():
- ### Query mantra nodes ###
- #mantra_path = hou.ui.selectNode(relative_to_node=None, initial_node=None, node_type_filter=hou.nodeTypeFilter.Rop)
- list_rops = []
- nodeType = houdini_nodes.get_best_node_type(hou.ropNodeTypeCategory(), 'mantra').name()
- for mantra_node in hou.node('/').allSubChildren():
- if mantra_node.type().name() == nodeType:
- list_rops.append(mantra_node)
- tree_nodes = {}
- for i in list_rops:
- tree_nodes[i.path()] = i.path()
- choices = hou.ui.selectFromTree(tree_nodes.keys(), 'Select mantra nodes')
- if len(choices) > 0:
- ropDict = {}
- for choice in choices:
- ropDict[choice] = choice
- mantra_path = ropDict.keys()[0]
- mNode = hou.node(mantra_path)
- for item in ropDict.keys():
- mNode = hou.node(item)
- ### Create dictionary of parms whcih need to be set to default ###
- parms_dict = {'trange':0, 'f1':mNode.parm('f1').revertToDefaults(), 'f2':mNode.parm('f2').revertToDefaults(), 'f3':mNode.parm('f3').revertToDefaults(), 'camera':'/obj/cam_main_STEREO_CAMERA'}
- ### Set values on the mantra nodes ###
- for key, value in parms_dict.items():
- mNode.setParms(parms_dict)
- [mantra_rop.setColor(hou.Color([1, 0, 0])) for mantra_rop in list_rops
- if mantra_rop.parm('forcelights').evalAsString() == '']
- **************************************************************************************************************************
- Match string and align nodes:
- node = hou.pwd()
- geo = node.geometry()
- incr = hou.frame() * 0.0001
- # Add code to modify contents of geo.
- # Use drop down menu to select examples.
- #get position of points in viewport
- total_points = geo.points()
- pos = []
- for pt in total_points:
- pos.append(pt.position())
- #get list of all nodes to align
- nulls = []
- for i in hou.node('/obj/geo1').children():
- if i.name().startswith('null'):
- nulls.append(i)
- #get current position of nodes in network view
- null_pos = []
- for null_node in hou.node('/obj/geo1').children():
- if null_node.name().startswith('null'):
- null_pos.append(null_node.position())
- values = zip(nulls, pos, null_pos)
- for a in values:
- node = a[0]
- posx = a[1][0]
- posy = a[1][1]
- posbx = a[2][0]
- posby = a[2][1]
- blendpx = hou.hscriptExpression('fit(@Frame, $RFSTART, $RFEND, {}, {})'.format(posbx, posx))
- blendpy = hou.hscriptExpression('fit(@Frame, $RFSTART, $RFEND, {}, {})'.format(posby, posy))
- node.setPosition(hou.Vector2(blendpx, blendpy))
- ****************************************************************************************************************************
- Rotate nodes:
- import math
- #values
- theta1 = `chs('theta')`
- theta2 = `chs('s_theta')`
- r1 = `chs('radius')`
- r2 = `chs('s_radius')`
- node = hou.pwd()
- geo = node.geometry()
- # Add code to modify contents of geo.
- # Use drop down menu to select examples.
- snode_pos = node.position()
- nnode = node.inputs()[0]
- nnode_pos = nnode.position()
- center = snode_pos
- target = nnode_pos
- frame = hou.frame()
- incr = frame * 0.001
- mean_pos = (abs(snode_pos[0]-nnode_pos[0]), abs(snode_pos[1]-nnode_pos[1]))
- #co-ordinates
- x1_pos = r1 * math.sin(theta1)
- y1_pos = r1 * math.cos(theta1)
- x2_pos = r2 * math.sin(theta2)
- y2_pos = r2 * math.cos(theta2)
- op1 = `ch('rotate_input')`
- op2 = `ch('rotate_self')`
- op3 = `ch('rotate_both')`
- #set position
- if(op1 is 1):
- nnode.setPosition(hou.Vector2(snode_pos[0] + x1_pos, snode_pos[1] + y1_pos))
- if(op2 is 1):
- node.setPosition(hou.Vector2(nnode_pos[0] + x1_pos, nnode_pos[1] + y1_pos))
- if(op3 is 1):
- nnode.setPosition(hou.Vector2(mean_pos[0] + x1_pos, mean_pos[1] + y1_pos))
- node.setPosition(hou.Vector2(mean_pos[0] - x2_pos, mean_pos[1] - y2_pos))
- ****************************************************************************************************************************
- Pop-up parameters:
- node = hou.node(hou.selectedNodes()[0].path())
- desktop = hou.ui.curDesktop();
- pane = desktop.createFloatingPane(hou.paneTabType.Parm);
- pane.setCurrentNode(node);
- pane.setPin(True);
- ****************************************************************************************************************************
- Create objectmerge node:
- import hou
- def main():
- nodeType1 = 'object_merge'
- nodeType2 = 'geo'
- nodeTypeOut = 'dd::mantra::1'
- choose = hou.ui.displayMessage('Location', buttons=('SOP', 'OBJ'))
- for node in hou.selectedNodes():
- tmpName = node.name()
- new_name = re.sub('OUT_', '', tmpName)
- nodeName = new_name
- geoName = new_name
- nodePath = node.path()
- nodePos = node.position()
- directory = node.path().split(node.name())[0]
- parentNode1 = hou.node(directory)
- parentNode2 = hou.node('/obj')
- parentNodePath = parentNode1.path()
- parentNodePos = parentNode1.position()
- parentOut = hou.node('/out')
- if(choose == 0):
- object_merge_node = createObjMergeNode(nodeType1, nodeName, parentNode1)
- object_merge_node.setPosition(hou.Vector2(nodePos[0], nodePos[1]-1))
- object_merge_node.setColor(hou.Color([0.188, 0.529, 0.459]))
- object_merge_node.setParms({'objpath1':'{}'.format(nodePath)})
- object_merge_node.setParms({'xformtype':1})
- else:
- render_node = createObjRenderNode(nodeType2, nodeName, parentNode2, parentNode1)
- render_node.setPosition(hou.Vector2(parentNodePos[0], parentNodePos[1]-1))
- render_node.setColor(hou.Color([0.322, 0.259, 0.58]))
- #render_node.setName('RENDER_{}'.format(parentNode1.name()), unique_name=True)
- parentNode3 = hou.node(render_node.path())
- object_merge_node2 = createObjMergeNode2(nodeType1, nodeName, parentNode3)
- object_merge_node2.setColor(hou.Color([0.188, 0.529, 0.459]))
- object_merge_node2.setParms({'objpath1':'{}'.format(nodePath)})
- object_merge_node2.setParms({'xformtype':1})
- ### create mantra node ###
- mantra_node = createMantraNode(nodeTypeOut, new_name, parentOut)
- mantra_node.parm('forceobject').set(render_node.name())
- mantra_node.parm('vobject').set('')
- mantra_node.parm('alights').set('')
- def createObjMergeNode(nodeType1, nodeName, parentNode1):
- object_merge_node = parentNode1.createNode(nodeType1)
- object_merge_node.setName('IN_{}'.format(nodeName), unique_name=True)
- return object_merge_node
- def createObjRenderNode(nodeType2, nodeName, parentNode2, parentNode1):
- render_node = parentNode2.createNode(nodeType2)
- for child in render_node.allSubChildren():
- child.destroy()
- render_node.setName('RENDER_{}'.format(nodeName), unique_name=True)
- return render_node
- def createObjMergeNode2(nodeType1, nodeName, parentNode3):
- object_merge_node2 = parentNode3.createNode(nodeType1)
- object_merge_node2.setName('IN_{}'.format(nodeName), unique_name=True)
- return object_merge_node2
- def createMantraNode(nodeTypeOut, new_name, parentOut):
- mantra_node = parentOut.createNode(nodeTypeOut)
- mantra_node.setName('{}'.format(new_name), unique_name=True)
- ***************************************************************************************************************************
- Source scripts form disk:
- import sys
- import traceback
- try:
- pythonScriptPath = '/home/yashp/Desktop/Scripts'
- if not pythonScriptPath in sys.path:
- sys.path.append(pythonScriptPath)
- import create_merge_switch_yashp
- create_merge_switch_yashp.main()
- except ImportError, e:
- print "cannot import script"
- except Exception, e:
- exc_type, exc_value, exc_traceback = sys.exc_info()
- print "*** print_exception:"
- traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout)
- ****************************************************************************************************************************
- Connect Nodes:
- import hou
- import math
- def main():
- limit = len(hou.selectedNodes())
- yPos = []
- for aNode in hou.selectedNodes():
- yPos.append([aNode.position()[1], aNode])
- yPos = sorted(yPos)
- for i in xrange(len(yPos) - 1):
- yPos[i][1].setInput(0,yPos[i+1][1])
- xPos = []
- for xNode in hou.selectedNodes():
- xPos.append([xNode.position()[1], xNode])
- xPos = sorted(xPos)
- ****************************************************************************************************************************
- Create Smoke Dops:
- import hou
- import re
- def main():
- for node in hou.selectedNodes():
- if hou.nodeTypeCategories().keys():
- ### Above function lets you call this function on any context ###
- dir = node.path().split(node.name())[0]
- nodeName = node.path().split('/')[-1]
- parentNode = hou.node(dir)
- nodeType1 = 'dopnet'
- nodeType2 = 'dopio'
- nodeType3 = 'bound'
- geo = node.geometry()
- condition0 = geo.prims()
- condition1 = geo.containsPrimType('VDB')
- condition2 = geo.containsPrimType('Volume')
- #nodeName
- dopnetName = hou.ui.readInput('Name the node', buttons=('OK', 'CANCEL'), initial_contents='')[1]
- #remove white spaces
- # otherName = 'DOPs_'+re.sub(r'\s+', '_', dopnetName)
- #remove special characters
- #otherName = re.sub('^[A-Za-z0-9]+]', '', rawOtherName)
- if dopnetName != '':
- nodeName = 'DOPs_{}'.format(dopnetName)
- nodeName2 = 'doi_{}'.format(dopnetName)
- nodeName3 = 'bounds_{}'.format(dopnetName)
- else:
- nodeName = 'DOPs_smoke'
- nodeName2 = 'doi_smoke'
- nodeName3 = 'bounds_smoke'
- #create dopnet regarless
- dopnet = createNode(nodeType1, nodeName, parentNode)
- dop_io = createNode(nodeType2, nodeName2, parentNode)
- bounds = createNode(nodeType3, nodeName3, parentNode)
- dopnetPath = dopnet.path()
- dop_io_path = dop_io.path()
- hou.hscript('oppresetload {} div_size'.format(dopnetPath))
- for aNode in dopnet.children():
- aNode.destroy()
- dopnet.setColor(hou.Color([0.576,0.208,0.475]))
- dop_io.setColor(hou.Color([1, 0.725, 0]))
- dop_io.setParms({'doppath' : '{}'.format(dop_io.relativePathTo(dopnet))})
- dop_io.setParms({'defobj' : 'smoke'})
- dop_io.setParms({'presets' : '0'})
- ### Setting node position ###
- selNodePos = node.position()
- dopnet.setPosition(hou.Vector2(selNodePos[0],selNodePos[1]-2))
- dop_io.setPosition(hou.Vector2(selNodePos[0], selNodePos[1]-2.8))
- bounds.setPosition(hou.Vector2(selNodePos[0]+1, selNodePos[1]-1))
- dopnet.setInput(0,node)
- dopnet.setInput(1, bounds)
- node.setSelected(False)
- bounds.setInput(0, node)
- #load preset based on type of entity
- if(len(condition0) == 0):
- # hou.hscript('oppresetload{}'.format(dopnet_particles_basic))
- smoke_object = hou.node('{}'.format(dopnetPath)).createNode('smokeobject', 'smoke')
- gas_resize = hou.node('{}'.format(dopnetPath)).createNode('gasresizefluiddynamic', 'gasresizefluiddynamic')
- source_gpfd = hou.node('{}'.format(dopnetPath)).createNode('gasparticletofield', 'density')
- source_gpft = hou.node('{}'.format(dopnetPath)).createNode('gasparticletofield', 'temperature')
- source_gpfv = hou.node('{}'.format(dopnetPath)).createNode('gasparticletofield', 'vel')
- merge = hou.node('{}'.format(dopnetPath)).createNode('merge', 'merge')
- smoke_solver = hou.node('{}'.format(dopnetPath)).createNode('smokesolver::2.0', 'smokesolver')
- output = hou.node('{}'.format(dopnetPath)).createNode('output', 'OUTPUT')
- merge.setInput(0, source_gpfd)
- merge.setInput(1, source_gpft)
- merge.setInput(2, source_gpfv)
- smoke_solver.setInput(0, smoke_object)
- smoke_solver.setInput(1, gas_resize)
- smoke_solver.setInput(4, merge)
- output.setInput(0, smoke_solver)
- output.setDisplayFlag(True)
- else:
- # hou.hscript('oppresetload{}'.format(dopnet_smoke_basic))
- smoke_object = hou.node('{}'.format(dopnetPath)).createNode('smokeobject', 'smoke')
- gas_resize = hou.node('{}'.format(dopnetPath)).createNode('gasresizefluiddynamic', 'gasresizefluiddynamic')
- source_vol = hou.node('{}'.format(dopnetPath)).createNode('sourcevolume', 'sourcevolume_density')
- smoke_solver = hou.node('{}'.format(dopnetPath)).createNode('smokesolver::2.0', 'smokesolver')
- output = hou.node('{}'.format(dopnetPath)).createNode('output', 'OUTPUT')
- smoke_solver.setInput(0, smoke_object)
- smoke_solver.setInput(1, gas_resize)
- smoke_solver.setInput(4, source_vol)
- output.setInput(0, smoke_solver)
- output.setDisplayFlag(True)
- for aNode in dopnet.children():
- aNode.moveToGoodPosition(relative_to_inputs=True)
- def createNode(nodeType1, nodeName, parentNode):
- dopnet = parentNode.createNode(nodeType1)
- dopnet.setName(nodeName, unique_name=True)
- return dopnet
- def createNode(nodeType2, nodeName2, parentNode):
- dop_io = parentNode.createNode(nodeType2)
- dop_io.setName(nodeName2, unique_name=True)
- return dop_io
- def createNode(nodeType3, nodeName3, parentNode):
- bounds = parentNode.createNode(nodeType3)
- bounds.setName(nodeName3, unique_name=True)
- return bounds
- ****************************************************************************************************************************
- Create merge switch:
- import hou
- def main():
- # well just use one of the selected nodes to get the pwd and
- # make the merge
- approvedCategories = ["Sop", "Cop2", "Driver", "Chop", "Dop"]
- if hou.selectedNodes():
- node = hou.selectedNodes()[0]
- else:
- None
- curCategory = node.type().category().name()
- nodeType = hou.ui.displayMessage("Merge or Switch?", buttons=("Merge", "Switch", "Cancel"))
- if nodeType == 2:
- None
- # Ask if we want to gather the inputs
- count = 0
- for aNode in hou.selectedNodes():
- if aNode.outputs():
- count += 1
- if count >= 1:
- result = hou.ui.displayMessage("Gather connections?", buttons=("Yes", "No", "Cancel"))
- else:
- result = 1
- if result == 2:
- None
- if curCategory in approvedCategories:
- if nodeType == 1:
- mergeNode = node.parent().createNode("switch", "switch")
- else:
- mergeNode = node.parent().createNode("merge", "merge")
- # We will get the lowest pos from the selected nodes so that
- # we can place the merge below this. We will also take the
- # average x pos to place them merge in the middle of the
- # selection
- xPositions = []
- yPositions = []
- nodes = []
- for aNode in hou.selectedNodes():
- nodes.append( [aNode.position()[0], aNode] )
- xPositions.append( aNode.position()[0] )
- yPositions.append( aNode.position()[1] )
- xPos = sum(xPositions)/float(len(xPositions))
- # If the nodes are right on top of each other, place the merge off to a side
- if xPos == max(set(xPositions), key=xPositions.count):
- xPos += 3
- yPos = min(yPositions)
- mergeNode.setPosition( hou.Vector2(xPos, yPos-1.5) )
- # Sort the nodes by their x pos so it connects them to the
- # merge in the correct order
- nodes.sort()
- # Pick up all the outputs from the nodes being merged
- # and set the inputs on the merge and whatnot
- for i in xrange(len(nodes)):
- # Try to set the input. If there is some error we will
- # just skip. This happens if one of the selected nodes
- # is a rop node or a chopnet, something like that.
- if result == 0:
- for outputs in nodes[i][1].outputs():
- x = 0
- for inputs in outputs.inputs():
- if nodes[i][1].name() == inputs.name():
- outputs.setInput(x, mergeNode)
- x += 1
- try:
- mergeNode.setNextInput(nodes[i][1])
- except:
- pass
- # Set selections and display flags where proper
- mergeNode.setCurrent(True, clear_all_selected=True)
- if curCategory == "Sop":
- mergeNode.setDisplayFlag(True)
- mergeNode.setRenderFlag(True)
- ****************************************************************************************************************************
- Create Null Node:
- import hou
- def main():
- node = hou.pwd()
- for i in hou.selectedNodes():
- if hou.nodeTypeCategories().keys():
- ### Above function lets you call this function on any context ###
- dir = i.path().split(i.name())[0]
- selNodeName = i.path().split('/')[-1]
- otherName = hou.ui.readInput('Name the node', buttons=('OK', 'CANCEL'), initial_contents='name_the_node')[1]
- if otherName == "":
- null = hou.node('/%s'%dir).createNode('null', 'OUT_%s'%selNodeName)
- else:
- null = hou.node('/%s'%dir).createNode('null', 'OUT_%s'%otherName)
- selNodePos = i.position()
- null.setColor(hou.Color( [0,0,0] ))
- ### Setting node position ###
- null.setPosition(hou.Vector2(selNodePos[0],selNodePos[1]-1))
- null.setInput(0,i)
- i.setSelected(False)
- null.setSelected(True)
- ### Setting render and display flags for respective contexts ###
- curContext = i.type().category().name()
- if curContext in ['Dop','Chop','Pop']:
- null.setDisplayFlag(True)
- if curContext in ['Sop', 'Cop2', 'CopNet']:
- null.setRenderFlag(True)
- null.setDisplayFlag(True)
- if curContext in ['Vop']:
- null.setPosition(hou.Vector2(selNodePos[0]+1.5,selNodePos[1]))
- null.setInput(0,i)
- ### Match the name of incoming nodes to that of the names of the nodes you have selected
- for aNode in i.outputs():
- x = 0
- for inputs in aNode.inputs():
- if inputs.name() == i.name():
- aNode.setInput(x,null)
- else:
- x += 1
- null.setInput(0,i)
- ****************************************************************************************************************************
- Create ObjMerge Node:
- import hou
- def main():
- for node in hou.selectedNodes():
- pathToNode = node.path()
- parentName = pathToNode.split( "/" )[-3]
- splitPath = pathToNode.split( "/" )[-1]
- nameOfNode = parentName + "_" + splitPath
- countPath = len( "%s"%splitPath )
- dir = pathToNode[:-countPath]
- objMerge = hou.node( "%s"%dir ).createNode( "object_merge", "IN_%s"%nameOfNode )
- selNodePos = node.position()
- objMerge.setPosition( hou.Vector2( selNodePos[0], selNodePos[1] - 1.5) )
- objMerge.setParms( { "objpath1" : "%s"%pathToNode } )
- objMerge.setColor( hou.Color( [ 0.6,0.4,0.2 ] ) )
- ****************************************************************************************************************************
- Disconnect nodes:
- import hou
- def main():
- for i in hou.selectedNodes():
- node = i.path()
- numNodesConnected = len(i.inputs())
- for aNode in i.inputs():
- nameNodesConnected = aNode.name()
- hou.hscript("opunwire %s 0"%node)
- ****************************************************************************************************************************
- Set Farm Options:
- import hou
- import IEHoudiniFx
- import IECore
- def main():
- ieRop = []
- for node in hou.node( "/obj" ).allSubChildren():
- if node.type().name().find( "ieSopRop" ) != -1:
- ieRop.append( node )
- treeNodes = {}
- for i in ieRop:
- treeNodes[ i.path() ] = IEHoudiniFx.FnRop( i )
- choices = hou.ui.selectFromTree( treeNodes.keys(), message="Select from List" )
- if len( choices ) > 0:
- ropDict = {}
- for choice in choices:
- ropDict[ choice ] = IEHoudiniFx.FnRop( choice )
- rop = ropDict.keys()[0]
- parms = []
- init = []
- for parm in hou.node( rop ).parms():
- if parm.name().find( "farmCores" ) != -1:
- parms.append( parm.name() )
- init.append( "8" )
- if parm.name().find( "farmMemory" ) != -1:
- parms.append( parm.name() )
- init.append( "15" )
- if parm.name().find( "farmClumping" ) != -1:
- parms.append( parm.name() )
- init.append( "25" )
- if parm.name().find( "ieFileType" ) != -1:
- parms.append( parm.name() )
- init.append( "bgeo.sc" )
- if parm.name().find( "ieVersionDescription" ) != -1:
- parms.append( parm.name() )
- enterValues = hou.ui.readMultiInput( message="Enter Rop Info", input_labels=( parms ), buttons=( 'OK', 'CANCEL' ), initial_contents=( init ) )[1]
- assignCores = enterValues[0]
- assignMemory = enterValues[1]
- assignFarmClumping = enterValues[2]
- assignFileType = enterValues[3]
- assignVerDescription = enterValues[4]
- defCores = hou.node( rop ).parm( "farmCores" ).eval()
- defMemory = hou.node( rop ).parm( "farmMemory" ).eval()
- defFarmClumping= hou.node( rop ).parm( "farmClumping" ).eval()
- defFileType = hou.node( rop ).parm( "ieFileType" ).evalAsString()
- defDescription = hou.node( rop ).parm( "ieVersionDescription" ).evalAsString()
- if defCores != assignCores:
- hou.node( rop ).setParms( { "farmCores" : "%s"%assignCores } )
- else:
- defCores = defCores
- if defMemory != assignMemory:
- hou.node( rop ).setParms( { "farmMemory" : "%s"%assignMemory } )
- else:
- defMemory = defMemory
- if defFarmClumping != assignFarmClumping:
- hou.node( rop ).setParms( { "farmClumping" : "%s"%assignFarmClumping } )
- else:
- defFarmClumping = defFarmClumping
- if defFileType != assignFileType:
- hou.node( rop ).setParms( { "ieFileType" : "%s"%assignFileType } )
- else:
- defFileType = defFileType
- if defDescription != "":
- defDescription = defDescription
- elif defDescription == "":
- hou.node( rop ).setParms( { "ieVersionDescription" : "%s"%assignVerDescription } )
- ****************************************************************************************************************************
- Ramp Copy:
- ####################################
- def checkRamps(node):
- rampList=[]
- for parm in node.parms():
- try:
- parm.evalAsRamp()
- rampList.append(parm)
- #print parm.name()
- except TypeError:
- name = parm.name()
- #print "not" + name
- return rampList
- ####################################
- def selectRamp(rampList):
- names = []
- count = 0
- for ramp in rampList:
- names.append( ramp.name())
- return hou.ui.selectFromList(names)
- ####################################
- selected = hou.selectedNodes()
- if len(selected)==2:
- origNode = hou.selectedNodes()[0]
- destNode = hou.selectedNodes()[1]
- origRamps = []
- destRamps = []
- origRamps = checkRamps(origNode)
- destRamps = checkRamps(destNode)
- origRamp = origRamps[selectRamp(origRamps)[0]]
- destRamp = destRamps[selectRamp(destRamps)[0]]
- ramp = origRamp.evalAsRamp()
- basis = ramp.basis()
- keys = ramp.keys()
- values = ramp.values()
- #print destRamp
- if ramp.isColor() is destRamp.evalAsRamp().isColor():
- destRamp.set( hou.Ramp(basis,keys,values))
- else:
- hou.ui.displayMessage("different type")
- else:
- print hou.ui.displayMessage("select 2 nodes")
- ****************************************************************************************************************************
- Add prefix to node name:
- import hou
- def main():
- for node in hou.selectedNodes():
- nameOfNode = node.name()
- nameEnter = hou.ui.readInput("Name the node", buttons=("OK", "CANCEL"), initial_contents='Asset_')[1]
- newName = "%s_"%nameEnter +"%s"%nameOfNode
- node.setName("%s"%newName)
- ****************************************************************************************************************************
- Set camera:
- viewports = hou.ui.paneTabOfType(hou.paneTabType.SceneViewer)
- viewports.curViewport().setCamera(hou.node("nameOfTheCamera")
- **************************************************************************************************************************
- Python Sop attrib sanity check:
- #######Paramters########
- ##Point Attribs(multiparmblock_list)##
- ##Label(aname#)##
- ##Type(atype#)##
- ##Check(check#)<toggle>##
- ##Weak sanity(weaksanity)##
- node = hou.pwd()
- geo = node.geometry()
- falseSanity = False
- message = ""
- attr_map = ["Float", "Int", "Float", "String"]
- for i in range(hou.parm("../pointattribs").eval()):
- if hou.parm("../check%d" % (i+1)).eval() is 0:
- continue
- aname = hou.parm("../aname%d" % (i+1)).evalAsString()
- #atype = hou.parm("../atype%d" % (i+1)).evalAsString()
- itype = int(hou.parm("../atype%d" % (i+1)).eval())
- stype = hou.parm("../atype%d" % (i+1)).menuLabels()[itype]
- attrib = geo.findPointAttrib(aname)
- if attrib is not None:
- aType = attrib.dataType()
- aSize = attrib.size()
- if aType.name() == attr_map[itype]:
- if itype==0 and aSize != 1:
- falseSanity = True
- message += "Attrib '%s' type doesn't match, is: %s, should be: %s\n" % (aname, "Vector", stype)
- if itype==2 and aSize != 3:
- falseSanity = True
- message += "Attrib '%s' type doesn't match, is: %s, should be: %s\n" % (aname, aType.name(), stype)
- else:
- falseSanity = True
- message += "Attrib '%s' type doesn't match, is: %s, should be: %s\n" % (aname, aType.name(), stype)
- else:
- falseSanity = True
- message += "Attrib: '%s' is missing\n" % aname
- if falseSanity and hou.parm("../weaksanity").eval() == 0:
- raise hou.NodeError(message)
- if falseSanity and hou.parm("../weaksanity").eval() == 1:
- raise hou.NodeWarning(message)
- **********************************************************************************************************************
- Isolate groups:
- def isoPtsByPrefix():
- node = hou.pwd()
- geo = node.geometry()
- prefix = node.parm( 'ptprefix' ).evalAsString()
- sP = node.position()[1]
- for ptGroup in geo.pointGroups():
- if ptGroup.name().startswith( prefix ):
- x = sP - 1.5
- blastNode = hou.node("..").createNode("blast","iso_%s"%ptGroup.name())
- blastNode.setPosition(hou.Vector2(sP, x))
- blastNode.setParms({'grouptype' : 3 })
- blastNode.setParms({'group' : ptGroup.name()})
- blastNode.setParms({"negate" : True})
- blastNode.setFirstInput(node)
- sP += 1
- def isoPrsByPrefix():
- node = hou.pwd()
- geo = node.geometry()
- prefix = node.parm( 'prprefix' ).evalAsString()
- sP = node.position()[1]
- for prGroup in geo.primGroups():
- if prGroup.name().startswith( prefix ):
- x = sP - 1.5
- blastNode = hou.node("..").createNode("blast","iso_%s"%prGroup.name())
- blastNode.setPosition(hou.Vector2(sP, x))
- blastNode.setParms({'grouptype' : 4 })
- blastNode.setParms({'group' : prGroup.name()})
- blastNode.setParms({"negate" : True})
- blastNode.setFirstInput(node)
- sP += 1
- def isoPtsBySuffix():
- node = hou.pwd()
- geo = node.geometry()
- suffix = node.parm( 'ptsuffix' ).evalAsString()
- sP = node.position()[1]
- for ptGroup in geo.pointGroups():
- if ptGroup.name().endswith( suffix ):
- x = sP - 1.5
- blastNode = hou.node("..").createNode("blast","iso_%s"%ptGroup.name())
- blastNode.setPosition(hou.Vector2(sP, x))
- blastNode.setParms({'grouptype' : 3 })
- blastNode.setParms({'group' : ptGroup.name()})
- blastNode.setParms({"negate" : True})
- blastNode.setFirstInput(node)
- sP += 1
- def isoPrsBySuffix():
- node = hou.pwd()
- geo = node.geometry()
- suffix = node.parm( 'prsuffix' ).evalAsString()
- sP = node.position()[1]
- for prGroup in geo.primGroups():
- if prGroup.name().endswith( suffix ):
- x = sP - 1.5
- blastNode = hou.node("..").createNode("blast","iso_%s"%prGroup.name())
- blastNode.setPosition(hou.Vector2(sP, x))
- blastNode.setParms({'grouptype' : 4 })
- blastNode.setParms({'group' : prGroup.name()})
- blastNode.setParms({"negate" : True})
- blastNode.setFirstInput(node)
- sP += 1
- def printPtGrps():
- node = hou.pwd()
- geo = node.geometry()
- ptgs = []
- for ptg in geo.pointGroups():
- ptgs.append( ptg )
- if not ptgs:
- node.setParms( { 'pointGrps' : 'GROUPS DO NOT EXIST' } )
- else:
- node.setParms( { 'pointGrps' : '%s'%[ i.name() for i in ptgs ] } )
- def printPrmGrps():
- node = hou.pwd()
- geo = node.geometry()
- prgs = []
- for prg in geo.primGroups():
- prgs.append( prg )
- if not prgs:
- node.setParms( { 'primGrps' : 'GROUPS DO NOT EXIST' } )
- else:
- node.setParms( { 'primGrps' : '%s'%[ i.name() for i in prgs ] } )
- def isoPrimGrps():
- node = hou.pwd()
- geo = node.geometry()
- inputNode = node.inputs()[0]
- groups = []
- sP = node.position()[1]
- for primGroup in geo.primGroups():
- x = sP - 1.5
- blastNode = hou.node("..").createNode("blast","iso_%s"%primGroup.name())
- blastNode.setPosition(hou.Vector2(sP, x))
- blastNode.setParms({'grouptype' : 4 })
- blastNode.setParms({'group' : primGroup.name()})
- blastNode.setParms({"negate" : True})
- blastNode.setFirstInput(node)
- sP += 1
- def isoPointGrps():
- node = hou.pwd()
- geo = node.geometry()
- inputNode = node.inputs()[0]
- groups = []
- sP = node.position()[1]
- for pointGroup in geo.pointGroups():
- x = sP - 1.5
- blastNode = hou.node("..").createNode("blast","iso_%s"%pointGroup.name())
- blastNode.setPosition(hou.Vector2(sP, x))
- blastNode.setParms({'grouptype' : 3 })
- blastNode.setParms({'group' : pointGroup.name()})
- blastNode.setParms({"negate" : True})
- blastNode.setFirstInput(node)
- sP += 1
- *******************************************************************************************************************
- Create null/output node with functions:
- import hou
- import re
- def main():
- node = hou.pwd()
- for i in hou.selectedNodes():
- if hou.nodeTypeCategories().keys():
- ### Above function lets you call this function on any context ###
- dir = i.path().split(i.name())[0]
- nodeName = i.path().split('/')[-1]
- nodeSel = hou.ui.displayMessage("Which type of node do you want to create?", buttons=('Null', 'Output'))
- if nodeSel == 0:
- nodeType = 'null'
- else:
- nodeType = 'output'
- # nodeName
- rawOtherName = hou.ui.readInput('Name the node', buttons=('OK', 'CANCEL'), initial_contents='geo')[1]
- # remove white spaces
- #otherName = re.sub(r'\s+', '', rawOtherName)
- # remove special characters
- otherName = 'OUT_'+re.sub(r'\W+', '_', rawOtherName)
- if rawOtherName != "":
- nodeName = otherName
- else:
- nodeName = 'OUT'
- parentNode = hou.node(dir)
- new_node = createNode(nodeType, nodeName, parentNode)
- new_node_pos = i.position()
- new_node.setColor(hou.Color([0, 0, 0]))
- new_node.setUserData("nodeShape", "circle")
- ### Setting node position ###
- new_node.setPosition(hou.Vector2(new_node_pos[0], new_node_pos[1] - 1))
- new_node.setInput(0, i)
- i.setSelected(False)
- new_node.setSelected(True)
- ### Setting render and display flags for respective contexts ###
- curContext = i.type().category().name()
- if curContext in ['Dop', 'Chop', 'Pop']:
- new_node.setDisplayFlag(True)
- if curContext in ['Sop', 'Cop2', 'CopNet']:
- new_node.setRenderFlag(True)
- new_node.setDisplayFlag(True)
- if curContext in ['Vop']:
- new_node.setPosition(hou.Vector2(new_node_pos[0] + 1.5, new_node_pos[1]))
- new_node.setInput(0, i)
- ### Match the name of incoming nodes to that of the names of the nodes you have selected
- for aNode in i.outputs():
- x = 0
- for inputs in aNode.inputs():
- if inputs.name() == i.name():
- aNode.setInput(x,new_node)
- else:
- x += 1
- new_node.setInput(0,i)
- def createNode(nodeType, nodeName, parentNode):
- new_node = parentNode.createNode(nodeType)
- new_node.setName(nodeName, unique_name=True)
- return new_node
- *********************************************************************************************************************
- Source scripts and reload:
- import sys
- import traceback
- try:
- pythonScriptPath = '/path/to/Script/on/disk'
- if not pythonScriptPath in sys.path:
- sys.path.append(pythonScriptPath)
- import name_of_script
- reload(name_of_script)
- name_of_script.main()
- except ImportError, e:
- print "cannot import script"
- except Exception, e:
- exc_type, exc_value, exc_traceback = sys.exc_info()
- print "*** print_exception:"
- traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout)
- ************************************************************************************************************************
- Copy Nodes To:
- srcPath = hou.selectedNodes()[0].parent().path()
- destPath = hou.ui.selectNode()
- destNode = hou.node( destPath )
- nodes = []
- for node in hou.selectedNodes():
- nodes.append( node )
- #dnodes = []
- #for dnode in hou.node( destPath ).children():
- # dnodes.append( dnode )
- #
- #for node in nodes:
- # for dnode in dnodes:
- # print compare( node, dnode )
- hou.copyNodesTo( nodes, hou.node( destPath ) )
- ************************************************************************************************************************
- Create viewport visualizers:
- import hou, toolutils, re, math, random
- def main():
- try:
- node = hou.selectedNodes()[0]
- geo = node.geometry()
- except IndexError:
- raised = hou.ui.displayMessage('You must select a node!', buttons=('OK',), severity=hou.severityType.ImportantMessage, default_choice=0, close_choice=0, title='OOPS!')
- if raised == 0:
- return 0
- attrib_list = []
- attrib_type_list = []
- floats = []
- vectors = []
- ints = []
- vector4s = []
- points_data_list = geo.pointAttribs()
- prims_data_list = geo.primAttribs()
- data_list = list(set(points_data_list + prims_data_list))
- for attr in data_list:
- if attr.dataType().name() == 'Float' and attr.size() == 3 and attr.name() != 'Cd':
- vectors.append(attr.name())
- if attr.dataType().name() == 'Float' and attr.size() == 4:
- vector4s.append(attr.name())
- if attr.dataType().name() == 'Int':
- ints.append(attr.name())
- if attr.dataType().name() == 'Float' and attr.size()==1:
- floats.append(attr.name())
- attrib_list.append(attr.name())
- sceneViewer = toolutils.sceneViewer()
- viewPort = sceneViewer.curViewport
- ### Create list of existing visualizers
- visualizersList = []
- visualizers = hou.viewportVisualizers.visualizers(category=hou.viewportVisualizerCategory.Scene)###Get current visualizers
- for viz in visualizers:
- visualizersList.append(viz.name())
- choices = hou.ui.selectFromList(attrib_list, exclusive=False, message='Choose attribute to visualize', title='Attribute List')
- if choices:
- vizType = hou.viewportVisualizers.types()[0]###Set the visualizers to be markers
- for choice in choices:
- if attrib_list[choice] in vectors:### Catch vectors
- createViz = hou.viewportVisualizers.createVisualizer(vizType, category=hou.viewportVisualizerCategory.Scene)
- createViz.setName(attrib_list[choice])
- createViz.setLabel(attrib_list[choice])
- createViz.setParm('attrib', attrib_list[choice])
- createViz.setParm('style', 4)
- createViz.setParm('class', 4)###Set to auto-detect entity
- createViz.setParm('arrowheads', 1)
- createViz.setParm('vectorcoloring', 0)
- #create random
- pi = math.pi
- e = math.e
- phi = math.log10(pi)
- seed = random.SystemRandom()
- red = seed.random() * pi
- green = seed.random() * e
- blue = seed.random() * phi
- #createViz.setParm('markercolor', red, green, blue)
- createViz.setParm('markercolorr', red)
- createViz.setParm('markercolorg', green)
- createViz.setParm('markercolorb', blue)
- createViz.setParm('markercolora',1)
- createViz.setParm('rangespec', 1)
- createViz.setParm('ramptype', 0)
- if attrib_list[choice] in floats:### Catch floats
- createViz = hou.viewportVisualizers.createVisualizer(vizType, category=hou.viewportVisualizerCategory.Scene)
- createViz.setName(attrib_list[choice])
- createViz.setLabel(attrib_list[choice])
- createViz.setParm('attrib', attrib_list[choice])
- createViz.setParm('style', 0)
- createViz.setParm('class', 4)
- if attrib_list[choice] in ints:### Catch ints
- createViz = hou.viewportVisualizers.createVisualizer(vizType, category=hou.viewportVisualizerCategory.Scene)
- createViz.setName(attrib_list[choice])
- createViz.setLabel(attrib_list[choice])
- createViz.setParm('attrib', attrib_list[choice])
- createViz.setParm('style', 0)
- createViz.setParm('class', 4)
- if attrib_list[choice] in vector4s:
- createViz = hou.viewportVisualizers.createVisualizer(vizType, category=hou.viewportVisualizerCategory.Scene)
- createViz.setName(attrib_list[choice])
- createViz.setLabel(attrib_list[choice])
- createViz.setParm('attrib', attrib_list[choice])
- createViz.setParm('style', 5)
- createViz.setParm('class', 4)
- def initial():
- ask = hou.ui.displayMessage('What would you like to do?', buttons=('Create new', 'Remove existing', 'Remove duplicates'), severity=hou.severityType.Message, default_choice=0, close_choice=0, title='Choose Operation')
- if ask == 0:
- main()
- if ask == 1:
- visualizers = hou.viewportVisualizers.visualizers(category=hou.viewportVisualizerCategory.Scene)
- for visualizer in visualizers:
- visualizer.destroy()
- if ask == 2:
- removeExisting()
- def removeExisting():
- visualizersList = []
- visualizers = hou.viewportVisualizers.visualizers(category=hou.viewportVisualizerCategory.Scene)###Get current visualizers
- for viz in visualizers:
- if re.split('[^\d]', viz.name())[-1]:
- viz.destroy()
Add Comment
Please, Sign In to add comment